Where to put Ruby helper methods for Rails controllers?

Ruby on-RailsRubyRuby on-Rails-3Ruby on-Rails-3.2View Helpers

Ruby on-Rails Problem Overview


I have some Ruby methods certain (or all) controllers need. I tried putting them in /app/helpers/application_helper.rb. I've used that for methods to be used in views. But controllers don't see those methods. Is there another place I should put them or do I need to access those helper methods differently?

Using latest stable Rails.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

You should define the method inside ApplicationController.

Solution 2 - Ruby on-Rails

For Rails 4 onwards, concerns are the way to go. There was a decent article which can still be viewed via the Wayback Machine.

In essence, if you look in your controllers folder you should see a concerns sub-folder. Create a module in there along these lines

module EventsHelper
  def do_something
  end
end

Then, in the controller just include it

class BadgeController < ApplicationController
  include EventsHelper

  ...
end

Solution 3 - Ruby on-Rails

you should define methods inside application controller, if you have few methods then you can do as follow

class ApplicationController < ActionController::Base    
  helper_method :first_method
  helper_method :second_method

  def first_method
    ... #your code
  end

  def second_method
    ... #your code
  end
end

You can also include helper files as follow

class YourController < ApplicationController
  include OneHelper
  include TwoHelper
end

Solution 4 - Ruby on-Rails

You can call any helper methods from a controller using the view_context, e.g.

view_context.my_helper_method

Solution 5 - Ruby on-Rails

Ryan Bigg response is good.

Other possible solution is add helpers to your controller:

class YourController < ApplicationController
  include OneHelper
  include TwoHelper
 end

Best Regards!

Solution 6 - Ruby on-Rails

Including helpers in controller will end-up exposing helper methods as actions!

# With new rails (>= 5) 

helpers.my_helper_method


# For console

helper.my_helper_method

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionat.View Question on Stackoverflow
Solution 1 - Ruby on-RailsRyan BiggView Answer on Stackoverflow
Solution 2 - Ruby on-RailsJohn ClearyView Answer on Stackoverflow
Solution 3 - Ruby on-RailsMuhamamd AwaisView Answer on Stackoverflow
Solution 4 - Ruby on-RailsDavidView Answer on Stackoverflow
Solution 5 - Ruby on-RailshyperrjasView Answer on Stackoverflow
Solution 6 - Ruby on-RailsAparichithView Answer on Stackoverflow