Using Helpers

Learn to work with Rails helper functions.

Earlier we said that it’s OK to put code in templates. Now we’re going to modify that statement. It’s perfectly acceptable to put some code in templates, because that’s what makes them dynamic. However, it’s poor style to put too much code in templates. Three main reasons for this stand out. First, the more code we put in the view side of our application, the easier it is to let discipline slip and start adding application-level functionality to the template code. This is definitely poor form, because we want to put application components in the controller and model layers so that it is available everywhere. This will pay off when we add new ways of viewing the application.

The second reason is that html.erb is basically HTML. When we edit it, we’re editing an HTML file. If we have the luxury of having professional designers create our layouts, they’ll want to work with HTML. Putting a bunch of Ruby code in there just makes it hard to work with.

The final reason is that code embedded in views is hard to test, whereas code split out into helper modules can be isolated and tested as individual units. Rails provides a nice compromise in the form of helpers. A helper is simply a module containing methods that assist a view. Helper methods are output-centric and exist to generate HTML or XML, or JavaScript, which are helpers that extend the behavior of a template.

Your own helpers

By default, each controller gets its own helper module. Additionally, there is an application-wide helper named application_helper.rb. Rails makes ...