Where are Rails helpers available?
Asked Answered
H

1

7

I'm referring to the modules you create in app/helpers. Are they available in:

  • Views?
  • Controllers?
  • Models?
  • Tests?
  • Other files?
  • Sometimes?
  • All the time?
Hotfoot answered 15/4, 2017 at 22:37 Comment(2)
The first chunk answers your question I believe, api.rubyonrails.org/classes/ActionController/Helpers.htmlTotalizer
The docs don't mention anything other than views and controllers. Also, I'm new to Ruby/Rails and I didn't understand what it meant about being accessible only through #helpers.Hotfoot
D
15

In Rails 5 all Helpers are available to all Views and all Controllers, and to nothing else.

http://api.rubyonrails.org/classes/ActionController/Helpers.html

These helpers are available to all templates by default.

By default, each controller will include all helpers.

In Views you can access helpers directly:

module UserHelper
  def fullname(user)
    ...
  end
end

# app/views/items/show.html.erb
...
User: <%= fullname(@user) %>
...

In Controllers you need the #helpers method to access them:

# app/controllers/items_controller.rb
class ItemsController
  def show
    ...
    @user_fullname = helpers.fullname(@user)
    ...
  end
end

You can still make use of helper modules in other classes by includeing them.

# some/other/klass.rb
class Klass
  include UserHelper
end

The old behavior was that all helpers were included in all views and just each helper was included in the matching controller, eg. UserHelper would only be included in UserController.

To return to this behavior you can set config.action_controller.include_all_helpers = false in your config/application.rb file.

Dewain answered 15/4, 2017 at 23:11 Comment(1)
One major gotcha when including helpers in other kinds of classes like Presenters/Decorators is that most of the view helpers rely on the view context. You need to get the view context either from the view (self) or by calling view_context from the controller and passing it as a constructor dependency or an argument.Ignominy

© 2022 - 2024 — McMap. All rights reserved.