Custom View Helpers in Rails 5
There is no need to declare:
in the application controller in Rails 5. Search for
helper :all exact match on github:
https://github.com/rails/rails/search?utf8=%E2%9C%93&q=%22helper+%3Aall%22&type=Code. You can see that in
if klass.superclass == ActionController::Base && ActionController::Base.include_all_helpers klass.helper :all end
helper :all is included if the
include_all_helpers flag is set to true.
We can create custom helpers in helpers directory without any declaration in the controllers to use it. Create a
jigolo_helper.rb in helpers directory.
module JigoloHelper def jiggle 'I can jiggle' end end
Now you can call this helper in any views. For instance, add this to the task index page.
<%= jiggle %>
The task index page will now display:
I can jiggle
Since Rails 3.1
include_all_helpers configuration is available to customize how helpers are included. According to the docs:
config.action_controller.include_all_helpers. By default
helper :allis done in
ActionController::Base, which includes all the helpers by default. Setting
falsewill result in including only
application_helperand the helper corresponding to controller (like
config.action_controller.include_all_helpersconfigures whether all view helpers are available everywhere or are scoped to the corresponding controller. If set to
UsersHelpermethods are only available for views rendered as part of
UsersHelpermethods are available everywhere. The default is
The default is nil and not true. The configuring document is wrong.
config.action_controller.include_all_helpers = false
to application.rb. It will look something like this:
module Blog class Application < Rails::Application config.action_controller.include_all_helpers = false end end
Restart the server and go to the tasks index page. You will get the error:
ActionView::Template::Error (undefined local variable or method `jiggle' for #<#<Class:0x00878>): 1: <h1> Tasks</h1> 2: 3: <%= jiggle %>
If you change the value to true or delete that entire configuration line, it will work.
In this article, you learned how to use custom helpers in Rails 5.