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 - Modifying the Generated View (Page 4 of 6 )
Next, we tell George to come over and have a look at the About page. He asks us why the hell we have put the text “Find me in app/views/about/index.rhtml” on the page. We explain to him that the page, or view as it is also called, was generated by Ruby on Rails, and that we can change it. He scribbles down something on a paper, which looks like a foreign mailing address, and gives it to us.
A view is where you put the code for the presentation layer that generates, for example, HTML or XML. Views are written in a template language called Embedded Ruby (ERB), which allows you to write Ruby code directly in the view. Here is an example of a view written in ERB that prints out the text “This is embedded Ruby code” to the browser.
<%# This is a comment and is not shown to the user %> <% text = "This is embedded Ruby code" %> <%= text %>
ERB code follows the syntax<% Ruby code %>, and <%= Ruby expression %>is used for printing out the value of an object to the browser. Comments are formatted as<%# comment %>.
ERB also allows you to prevent HTML injection by escaping the following special characters in content entered by users: &, <, >, and ". The following line outputs the text&<>to the browser, instead of&<>, by using theh method, which is short forhtml_escape.
<%= h('&<>') %>
The view we are going to change is located in theapp/viewsdirectory. This is the root directory for all views. Each view is stored in a subdirectory named after the controller. For example, if the path to your controller isapp/controllers/about_controller.rb, the path to that controller’s views isapp/views/about.
Openapp/views/about/index.rhtmlin an editor and change it as follows:
<p>Online bookstore located in downtown Manhattan, New York</p> <h2>Mailing Address</h2> <address> Emporium<br/> P.O. Box 0000<br/> Grand Cayman, Cayman Islands<br/> </address>
After saving the changes, go back to the browser and click the reload button. You should see the page shown in Figure 1-4.