Note: This example comes from Michael Hartl’s excellent RubyOnRails book. Go there for the full example.

Last post we saw how you could dynamically add content to your Rails page, and then extract common HTML using layouts.

app/views/layouts/application.html.erb

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
   <title>Ruby on Rails Tutorial Sample App | <%= @title %></title>
</head>
<body>
   <%= yield %>
</body>
</html>

But what if your controller doesn’t define a title attribute? Or it is null?
To define a base title class that will always have a default value we can use Rails helpers.

app/helpers/application_helper.rb

module ApplicationHelper

   # Return a title on a per-page basis.
   def title
      base_title = "Ruby on Rails Tutorial Sample App"
      if @title.nil?
         base_title
      else
         "#{base_title} | #{@title}"
      end
   end
end

This helper (which is tied to the application.html.erb file) can be used to set a default title for any page, and add a specific title if one is defined in a view.

Now instead of:

<title>Ruby on Rails Tutorial Sample App | <%= @title %></title>

We can have:

<title><%= title %></title>

Note: no @ sign in front of title here.

Helpers are Rails way of helping you separate presentation from logic. You can test and put logic in controllers and small helpers, and keep your UI clean by not cluttering it up with extra code.

To get the full (and much better) story on helpers be sure to check out Michael Hartl’s excellent book from where this example came.