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.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
<html lang="en" xml:lang="en" xmlns="">
   <title>Ruby on Rails Tutorial Sample App | <%= @title %></title>
   <%= yield %>

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.


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} | #{@title}"

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.