I understand I can put a helper method in a Helper
class inside the helper
folder in Rails. Then that method can be used in any view. And I understand I can put methods in the ApplicationController
class and that method can be used in any controller.
Where's the proper place to put a method that is frequently used in both controllers and views?
You can put a method in a controller and then call
helper_method
in the controller to indicate that this method is available as if it were in a helper too.For example:
This method will then be available to all controllers and to all views.
You can put it in the controller and call:
from the controller.
I put helpers like the ones you describe in a module in my
lib/
directory. Given someMyApp
application, this would go inapp/lib/my_app/helpers.rb
and look likeNext, you must require this module. Create a new initializer at
config/initializers/my_app.rb
that looks likeand make sure
config.autoload_paths
contains yourlib/
directory inconfig/application.rb
.Finally, include the module wherever you want to use it. Anywhere.
app/controllers/application_controller.rb
app/helpers/application_helper.rb
I think this is a cleaner, more testable approach to managing reusable helpers throughout your application.