Ruby On Rails Lesson
We’ve achieved a lot already in this section, generating three valid pages using Rails controllers and actions, but they are purely static HTML and hence don’t show off the power of Rails. Moreover, they suffer from terrible duplication:
- The page titles are almost (but not quite) exactly the same.
- ‘‘Ruby on Rails Tutorial Sample App’’ is common to all three titles.
- The entire HTML skeleton structure is repeated on each page.
This repeated code is a violation of the important ‘‘Don’t Repeat Yourself’’ (DRY) principle; in this section and the next we’ll ‘‘DRY out our code’’ by removing the repetition. Paradoxically, we’ll take the first step toward eliminating duplication by first adding some more: We’ll make the titles of the pages, which are currently quite similar, match exactly. This will make it much simpler to remove all the repetition at a stroke.
The technique involves using Embedded Ruby in our views. Since the Home, Help, and About page titles have a variable component, we’ll use a special Rails function called provide to set a different title on each page. We can see how this works by replacing the literal title ‘‘Home’’ in the home.html.erb view with the code in Listing 3.22.
Listing 3.22 The view for the Home page with an Embedded Ruby title.