Reputation: 448
I am following the book Agile Development with Rails(http://www.amazon.com/Agile-Development-Rails-Pragmatic-Programmers/dp/1934356549). In Chapter 9, it defines a private method in application controller:
class ApplicationController < ActionController::Base
protect_from_forgery
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 "This makes this method only available to other controllers, and in particular it prevents Rails from ever making it available as an action on the controller." I am wondering why this will make a private method available to other controllers? Iknow private methods can only be accessible inside the same class. Is there any magic behind this?
Upvotes: 0
Views: 2011
Reputation: 1652
Private methods in ruby don't work the same way as they do in other languages. In ruby we can call a private method from within the class it is declared in as well as all subclasses of that class. This explains why you can declare a private method in ApplicationController and have it available in all other controllers, as all of your other controllers are inherited from ApplicationController.
For more information I suggest researching ruby access control. To start, there is a great article here.
Hope this helps!
Upvotes: 5