Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where are Rails helpers available?

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?
like image 927
Adam Zerner Avatar asked Apr 15 '17 22:04

Adam Zerner


People also ask

What is helpers folder in Rails?

What are helpers in Rails? A helper is a method that is (mostly) used in your Rails views to share reusable code. Rails comes with a set of built-in helper methods. One of these built-in helpers is time_ago_in_words .

Where are custom view helpers stored within a standard Rails app?

Custom helpers for your application should be located in the app/helpers directory.


1 Answers

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.

like image 136
Gaston Avatar answered Sep 25 '22 02:09

Gaston