Displaying Object Contents with Exceptions
Problem
When working on an a controller's action in development, you want to inspect the contents of any object in your browser.
Solution
Use the raise method of the Kernel module, passing it the string representation of an object as the only argument. This triggers a RuntimeError exception that outputs the contents of the string argument to your browser when the action is invoked. For example, to get a quick dump of all the student records contained in the @students instance variable, you could use raise like this:
def list
@student_pages, @students = paginate :students, :per_page => 10
raise @students.to_yaml
end
Now when you try to view the student list with a browser, you should see the standard Rails error page complaining about a RuntimeError in StudentsController#list, as expected, but you'll also see the YAML output of the @students object:
---
- !ruby/object:Student
attributes:
name: Jack
class: "Junior"
id: "1"
- !ruby/object:Student
attributes:
name: Sara
class: "Senior"
id: "2"
- !ruby/object:Student
attributes:
name: Emily
class: "Freshman"
id: "3"
Discussion
While triggering exceptions isn't the most elegant debugging solution, it's often all you need to quickly inspect the content of a variable. The benefit is that you don't have to alter your view code at all.
See Also
|