开发者

Ruby on Rails: Global Helper method for all controllers

开发者 https://www.devze.com 2023-01-04 07:36 出处:网络
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 viewsYou can add the method to A

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/

0

精彩评论

暂无评论...
验证码 换一张
取 消