How do I set u开发者_StackOverflow社区p a method that I want accessible from all controllers?
Sticking the method in application_helper just makes it available to the views
You can add the method to ApplicationController
. All the other controllers subclass ApplicationController
, so will be able to call the method.
You'll want to make the method protected
so that it is only visible to subclasses and isn't available as a web-accessible action.
You can include ApplicationHelper
in your controllers (or base ApplicationController) to make the helper methods available.
You can also include the following line in your ApplicationController to include all helpers:
helper :all
Stick it into lib
. Helpers are meant to be used in views; if you have application-specific libraries (and by "libraries" I mean any code that your application uses, and by "application-specific" anything that doesn't belong into vendor
), lib
is the place to go.
Here is very good example
http://railscasts.com/episodes/64-custom-helper-modules
In rails 3 you can use: the view_context object in your controller to access view helper methods. For example,
class ApplicationController < ActionController::Base
def some_method
view_context.some_view_helper_method
end
end
module ApplicationHelper
def some_view_helper_method
end
end
Check out this: http://wowkhmer.com/2011/09/09/use-view-helper-methods-in-rails-3-controller/
精彩评论