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
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
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
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
If there will be any conflict in the same names of methods in different helper modules, rails will use method from latter file (alphabetically).