In this second part of a multi-part series on the Action Pack library in Ruby-on-Rails, you'll learn about Action View and the way its templates use Embedded Ruby code (ERb). This article is excerpted from chapter six of the book Beginning Rails: From Novice to Professional, written by Jeffery Allan Hardy, Cloves Carneiro Jr. and Hampton Catlin (Apress; ISBN: 1590596862).
The Action View library is the second half of Action Pack. Given that controllers are responsible for handling the request and issuing a response, views are responsible for rendering the output of a response in a way a browser (or any other user agent) can understand. Letís say you requested the index action from theEventsController. After performing the logic to retrieve a list of events, the controller hands off to the view, which formats the list of events to make them look pretty. The controller then collects the results of the render, and the HTML is sent back to the browser, thus completing the request cycle.
While the controller and the view are separate entities, they need to communicate with each other. The primary mechanism by which they do this is through shared variables. These shared variables are called instance variables and are easy to spot in Ruby because they are prefixed with the@symbol. Keep this in mind as you look at the following view example in which we use an instance variable called@eventsto produce an event listing:
<html> <body> <ul> <% for event in @events %> <li><%= event.title %></li> <% end %> <ul> </body> </html>
Even without knowing any Ruby, you should be able to guess what this code does: it iterates over the collection of events stored in the variable@eventsand prints the title for each between HTML list-item (<li>) tags. If@eventscontained three events whose titles were One, Two, and Three, respectively, the preceding code would be compiled to the following:
At this point, you might be wondering where the variable@eventscame into being. If you guessed in the controller, you would be right. The controller sets up instance variables that the view can access. In this case, the controller created a variable called@eventsand the view was given automatic access to it. Notice that the view doesnít perform any logic to fetch the list of events; it simply relies on the controller to have set up the variable and performs the display logic necessary to turn the collection into a browser-ready HTML list.