11

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.

pjmorse
  • 9,204
  • 9
  • 54
  • 124
Arcath
  • 4,331
  • 9
  • 39
  • 71

2 Answers2

26

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
pjmorse
  • 9,204
  • 9
  • 54
  • 124
tsdbrown
  • 5,038
  • 3
  • 36
  • 40
  • 3
    According to @BrandonTilley comment [here](http://stackoverflow.com/questions/5791211/how-do-i-extract-rails-view-helpers-into-a-gem#comment-42572499) you should use `ActiveSupport.on_load( :action_view ){ include MyGem::ViewHelpers }` instead of `send :include` as of ActiveSupport 3.0.0. More details in linked SO thread. – plunntic iam Aug 28 '15 at 22:26
3

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
reto
  • 16,189
  • 7
  • 53
  • 67