Helper methods to be used in Controllers AND Views in Rails

6.2k views Asked by At

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?

3

There are 3 answers

0
Marek Lipka On BEST ANSWER

You can put it in the controller and call:

helper_method :my_method

from the controller.

0
Shadwell On

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:

class ApplicationController

  helper_method :this_is_really_useful

  def this_is_really_useful
    # Do useful stuff
  end

This method will then be available to all controllers and to all views.

0
deefour On

I put helpers like the ones you describe in a module in my lib/ directory. Given some MyApp application, this would go in app/lib/my_app/helpers.rb and look like

module MyApp
  module Helpers
    extend self

    def some_method
      # ...
    end 

  end
end

Next, you must require this module. Create a new initializer at config/initializers/my_app.rb that looks like

require 'my_app'

and make sure config.autoload_paths contains your lib/ directory in config/application.rb.

config.autoload_paths += Dir["#{config.root}/lib",
                             # other paths here...
                            ]

Finally, include the module wherever you want to use it. Anywhere.

app/controllers/application_controller.rb

class ApplicationController < ActionController::Base

  include MyApp::Helpers

app/helpers/application_helper.rb

module ApplicationHelper
  include MyApp::Helpers

I think this is a cleaner, more testable approach to managing reusable helpers throughout your application.