Rails 4 recipes and know-how for developers

less theoretical words, more examples in 'developers friendly' way

Custom View Helpers in Rails 4

After this article (based on simple example) you will know how to quickly create custom view helpers. Let’s look at the following code:

1
2
3
4
<tr class="activeRow">            
  <td><%= number_to_currency(@value1, separator: ",", delimiter: "", format: '%n') %></td>
  <td><%= number_to_currency(@value2, separator: ",", delimiter: "", format: '%n') %></td>
</tr>

As you see, there is some code duplication. Instead of using rails number_to_currency view helper we need define separator, delimiter, format every time we want to use it. It’s time to write custom view helper which encapsulates all this duplicated stuff.

In Rails 4 application there is default app directory structure, which looks like this:

1
2
3
4
5
6
7
app/
   assets/
   controllers/
   helpers/  <-- helpers directory
   mailers/
   models/
   views/

There is helpers directory. You can create your own modules there or use default one: ApplicationHelper, which should exists in this dir. Let’s create your own module.

1
2
3
4
5
6
# app/helpers/my_custom_helper.rb
module MyCustomHelper
  def my_formatted_number number
    number_to_currency(number, separator: ",", delimiter: "", format: '%n')
  end
end

As you see helpers are modules which are mixed with views by Rails (in background) and their methods are available in Views. To use newly created helper just type:

1
2
3
4
<tr class="activeRow">            
  <td><%= my_formatted_number(@value1) %></td>
  <td><%= my_formatted_number(@value2) %></td>
</tr>

If there will be any conflict in the same names of methods in different helper modules, rails will use method from latter file (alphabetically).

Comments