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.
In Rails 5, by using the new instance level helpers method in the controller, we can access helper methods in controllers.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With