简体   繁体   中英

Ruby on Rails: Global Helper method for all controllers

How do I set up 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.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM