Search code examples
ruby-on-railsrubymethodsprivate

Rails: what are the main reasons for making methods private?


If the end_user cannot access the source code of the app, why we still need to make some methods private?

I'm reading the Pragmatic Agile Web Development with Rails and I couldn't understand why we need to make the following method private (even after reading the explanation):

private
  def current_cart Cart.find(session[:cart_id])
   rescue ActiveRecord::RecordNotFound 
   cart = Cart.create 
   session[:cart_id] = cart.id
   cart
   end 
end

It says that it will never allow Rails to make it available as an action, but as a coder, why would I ever do that myself?


Solution

  • As you say there may be no external reason to make it private. However, it also prevents you — or somebody else using your code — from accidentally making use of the method where you're not supposed to.

    See it as a sanity check on your own future behaviour if you will.