The Action Pack library for Rails handles the chain of events that starts when a user makes a request to a Ruby-on-Rails application. This article series gives you an overview of the library, and then walks you through using it in a sample application. It's 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).
When you type a URL into your browser’s address bar and click enter, a few things happen behind the scenes. First, the URL is translated into a unique address by which the server that hosts the application can be identified. The request is then sent to that server, which begins a chain of events that culminates in a response. The response is usually, but not always, in the form of an HTML document, which is essentially a text document full of special codes that your browser understands and can render visually on your screen. At this point, the request cycle is complete, and the browser waits for further input from you. If you click a link somewhere on the page, or type a new URL in the address bar, the cycle begins all over again: the request is sent, the server processes it, and the server sends back the response.
When you make a request to a Rails application, this request cycle is the responsibility of a component of Rails called Action Pack. The Action Pack library is an integral component of the Rails framework and one that you’ll need to get quite familiar with if you intend to master Rails.
In this chapter, we’ll begin with an overview of Action Pack, and then get to work using it in our sample events application.
Action Pack Components
We already discussed the MVC pattern, but in case you need a refresher, here it is. The model is your application’s world, most often represented by database objects, like articles, comments, or subscribers. The controller is the grand orchestrator, dealing with requests and issuing responses. The view is the code that contains instructions for rendering visual output for a browser, like HTML.
Armed with this refresher, you might be able to guess what roles are played by the Action Pack. Since this isn’t a test, we’ll give away the answer: Action Pack is the controller and the view. The controller performs the logic, and the view renders the template that is given back to the requesting browser. Not surprisingly, the two modules that make up Action Pack are named accordingly: Action Controller and Action View.
At this point, you might be wondering why the view and the controller are wrapped up in a single library, unlike models, which have a library of their own. The answer is subtle and succinct: controllers and views are very closely related. In the pages that follow, we’ll paint a more complete picture of both the role and the relationship of controllers and views, how they work, and how they work together to create and control the interface of a Rails application.