Debugging

There are some useful methods you can use to debug your template code if you're getting errors.

'Show Attributes'

show_attributes(object) is a Blueprint helper method that exposes the attributes of a model. For example, if you put

<%= show_attributes(@page) %>

at the top of blueprints/pge/index.html.erb and bring up a page using that template in your browser, you'll see a table of information about the page, like this:

show_attributes

This method works for any object - @post, @person, @page are all examples. As you can see, this is a useful way of confirming that the data you're asking for in your templates (ie, @page.title) exists, and is in the expected form (ie, "Layout and Yield").

Raise and Inspect

As with show_attributes, you can use inspect to make sure that the data you're relying upon is in fact the data you're getting from the model. The raise method forces your template code to stop executing at the point it occurs. When combined, these two methods are very powerful debugging tools.

Take this very simple example:

<% @posts.first(3) do |post| %>
  <%= post.title %>
<% end %>

This code will execute fine - but what happens if the first post title you see is not the one you're expecting?

You might try putting a raise and inspect before the code block, to make sure that the array contains the data you want:

<%= raise @posts.first(3).inspect %>

<% @posts.first(3) do |post| %>
  <%= post.title %>
<% end %>

The raise will stop the template executing and give you an exception message. The inspect will spit the contents of @posts.first(3) into the exception message so that you can scan it for information about what might be going wrong.

Raise is particularly useful in places where you're creating complicated looping or nested blocks, since it will allow you to check the status of your data (ie, the contents of an array or hash) at key places.

User notes

(You can add notes to this page using the form below.)


Only the note field is required.

Preview or