8.6. Accessing the Request and Response Environment

The last couple of examples do something very interesting: the first alters the HTTP headers for the response that is about to be sent, and the second accesses the HTTP REFERER of the request. This is neat, but Rails offers much more when it comes to accessing request and response information.

The following is a list of special identifiers that you can use from within your controller: action_name, cookies, headers, logger, params, request, and response.

Their names are self-descriptive: action_name is a method that returns the name of the current action; cookies represents the cookies for the request; headers is a hash of HTTP headers for the response; logger is a ActiveSupport::BufferedLogger object that's available throughout the application as discussed before; and params is the parameters hash.

request and response are objects that represent the request being processed and the response that is about to be sent, respectively.

You rarely have to modify the response object directly, because Rails takes care of formulating a proper response on its own. However, in the few circumstances where you need to alter the object before it's sent to the client, you can do so easily by accessing one or more of its attributes. Among these, the two that will most likely be used to alter the response object are body and headers.

request, on the other hand, is slightly more complex, and is used frequently enough to warrant further explanation. ...

Get Ruby on Rails® for Microsoft Developers now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.