Question

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?

Was it helpful?

Solution 2

You can put it in the controller and call:

helper_method :my_method

from the controller.

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top