Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a helper method with a gem

I have found a lot of information about adding form helper methods (see one of my other questions), but I can't find anything about adding helper methods as if they were defined in application_helper.rb.

I've tried copying application_helper.rb from a rails app into the gem but that didn't work.

I've also tried:

class ActionView::Helpers

..but that produces an error.

like image 707
Arcath Avatar asked Jul 06 '10 06:07

Arcath


People also ask

Can we use helper method in controller rails?

In Rails 5, by using the new instance level helpers method in the controller, we can access helper methods in controllers.

Can we call controller method in Helper?

You generally don't call controller-methods from helpers. That is: if you mean a method that collects data and then renders a view (any other method that needs to be called should probably not be in a controller). It is definitely bad practice and breaks MVC.


2 Answers

Create a module somewhere for your helper methods:

module MyHelper
  def mymethod
  end
end

Mix it into ActionView::Base (such as in init.rb or lib/your_lib_file.rb)

ActionView::Base.send :include, MyHelper
like image 92
tsdbrown Avatar answered Oct 11 '22 06:10

tsdbrown


To extends @sdbrown's excellent Answer to Rails 4:

# in in lib/my_rails_engine.rb
require 'my_rails_engine/my_rails_helper.rb'
require 'my_rails_engine/engine.rb'

And

# in lib/my_rails_engine/engine.rb
module MyRailsEngine
  class Engine < ::Rails::Engine
    initializer "my_rails_engine.engine" do |app|
      ActionView::Base.send :include, MyRailsEngine::MyRailsHelpers
    end
  end
end

and finally

# in lib/my_rails_engine/my_rails_helper.rb 
module MyRailsEngine
  module MyRailsHelpers
    # ...
    def your_helper_here
    end
  end
end
like image 39
reto Avatar answered Oct 11 '22 06:10

reto