22

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

DerNalia
  • 327
  • 1
  • 4
  • 11
  • here is another example: http://stackoverflow.com/questions/1179865/why-are-all-rails-helpers-available-to-all-views-all-the-time-is-there-a-way-t –  May 14 '13 at 14:00

5 Answers5

38

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.

Phil Ross
  • 25,590
  • 9
  • 67
  • 77
18

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
elektronaut
  • 2,547
  • 1
  • 18
  • 11
  • I didn't include ApplicationHelper, but what you said allowed me to create a shared.rb in app/controllers/ – DerNalia Jun 17 '10 at 16:18
10

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.

Amadan
  • 191,408
  • 23
  • 240
  • 301
1

Here is very good example

http://railscasts.com/episodes/64-custom-helper-modules

speedingdeer
  • 1,236
  • 2
  • 16
  • 26
0

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/

Will
  • 812
  • 3
  • 11
  • 21