Custom View Helpers in Rails 5


Step 1

There is no need to declare:

helper :all

in the application controller in Rails 5. Search for helper :all exact match on github: You can see that in actionpack/lib/action_controller/railties/helpers.rb.

if klass.superclass == ActionController::Base && ActionController::Base.include_all_helpers
  klass.helper :all

helper :all is included if the include_all_helpers flag is set to true.

Step 2

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'

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:

Added config.action_controller.include_all_helpers. By default helper :all is done in ActionController::Base, which includes all the helpers by default. Setting include_all_helpers to false will result in including only application_helper and the helper corresponding to controller (like foo_helper for foo_controller).

config.action_controller.include_all_helpers configures whether all view helpers are available everywhere or are scoped to the corresponding controller. If set to false, UsersHelper methods are only available for views rendered as part of UsersController. If true, UsersHelper methods are available everywhere. The default is true.

The default is nil and not true. The configuring document is wrong.

Step 3


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

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>
    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.

Related Articles

Watch this Article as Screencast

You can watch this as a screencast Custom View Helpers in Rails 5

Create your own user feedback survey