In this conclusion to a three-part series on how to do a project setup and proof of concept for a fictional bookstore on Ruby-on-Rails, we'll actually start the application for the first time and see how it functions. This article is excerpted from chapter one of the book Practical Rails Projects, written by Eldon Alameda (Apress; ISBN: 1590597818).
Testing a Book Emporium Application - Creating the Layout (Page 5 of 6 )
George is a bit happier now, but he says that the page is not as nice looking as the current Emporium website, which he tells us was designed eight and a half years ago by his then ten-year-old nephew. He agrees that Emporium needs a new site design, but he tells us that he just sent some money to his starving sister on the Cayman Islands. So we decide to implement a design that can be improved later, because it will take a month or two before George can afford a professional designer.
Layouts are used in Ruby on Rails for surrounding the content of your pages with a header and footer. Figure 1-5 illustrates the concept of Rails layouts and views. The example shows a typical page consisting of a header, content, and footer section.
Figure 1-5. Layouts and views
The same result can also be achieved by inserting the same header and footer code in all views, but this goes against the Don’t Repeat Yourself (DRY) principle, which states that you should avoid code duplication in all parts of your code.
Consider the following HTML for a page generated by Rails.
The layout contains four Ruby expressions that are all evaluated when the page is rendered. The first expression will allow us to set the page title by defining an instance variable in our controllers:
<%= @page_title || 'Emporium' %>
The default title, “Emporium,” is used if we don’t specify the@page_titlevariable in the controller.
The second expression includes the Emporium style sheet, which we’ll create in the next section.
The third expression allows us to use the title of the page as the page heading:
<%= "<h1>@page_title</h1>" if @page_title %>
If the instance variable@page_titlehas not been defined in the controller, then nothing is shown.
The last expression inserts the view part of the page by a call to theyieldmethod.