Recipe 10.7. Outputting Environment Information in Views


Problem

During development, or perhaps while trying to locate a bug, you want to display detailed output about the environment.

Solution

Use the debug Action View helper to display neatly formated YAML output of objects in your views. For example, to inspect the env hash for the current request, add this in your view:

<%= debug(request.env) %>

which displays the following:

---  SERVER_NAME: localhost PATH_INFO: /test HTTP_ACCEPT_ENCODING: gzip,deflate HTTP_USER_AGENT: Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O;    en-US; rv:1.8.0.4) Gecko/20060508 Firefox/1.5.0.4 SCRIPT_NAME: / SERVER_PROTOCOL: HTTP/1.1 HTTP_CACHE_CONTROL: max-age=0 HTTP_ACCEPT_LANGUAGE: en-us,en;q=0.5 HTTP_HOST: localhost:3000 REMOTE_ADDR: 127.0.0.1 SERVER_SOFTWARE: Mongrel 0.3.12.4 HTTP_KEEP_ALIVE: "300" HTTP_COOKIE: _session_id=c2394e2855118afd9c40453dcb2389f7 HTTP_ACCEPT_CHARSET: ISO-8859-1,utf-8;q=0.7,*;q=0.7 HTTP_VERSION: HTTP/1.1 REQUEST_URI: /test SERVER_PORT: "3000" GATEWAY_INTERFACE: CGI/1.2 HTTP_ACCEPT: text/xml,application/xml,application/xhtml+xml,text/html;   q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5 HTTP_CONNECTION: keep-alive REQUEST_METHOD: GET

For a very verbose look at your environment, add this to a view:

<h1>headers</h1> <%= debug(headers) %><hr /> <h1>params</h1> <%= debug(params) %><hr /> <h1>request</h1> <%= debug(request) %><hr /> <h1>response:</h1> <%= debug(response) %><hr /> <h1>session</h1> <%= debug(session) %><hr />

Discussion

The debug method places <pre> tags around the object you pass to it to preserve newline characters in HTML output. These tags are assigned a CSS class of debug_dump in case you want to further stylize the output. debug attempts to call the to_yaml method of the objects that respond to it. Otherwise, the fallback is to call the object's inspect method.

Here's a list of objects that are particularly useful when debugging, and a brief summary of what they contain:


headers

A hash containing the HTTP headers to be used in the response


params

A HashWithIndifferentAccess containing all current request parameters


request

A CgiRequest object containing detailed information about the incoming request


response

A CgiResponse object containing details about how the response is to be handled


session

A CGI::Session object containing a hash of the data currently in the session

You might find it helpful to dump the contents of the session object, for example, in the footer of your application's layout template while debugging session-related problems.

See Also

  • Section 10.8"




Rails Cookbook
Rails Cookbook (Cookbooks (OReilly))
ISBN: 0596527314
EAN: 2147483647
Year: 2007
Pages: 250
Authors: Rob Orsini

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net