Ever tried to get a sense of an ActiveRecord object by squinting though output like this?
>> User.find_by_login("Michael Hoffman").recipes.last
=> #<Recipe id: 18891, title: "Pasta with Lemon-Parmesan Butte
r", created_at: "2012-08-29 00:03:55", updated_at: "2012-08-29
16:20:58", description: "I was walking by a little pizzeria in
the East Vill...", recipe_category_id: 36, serving_size: "4 as
a pasta course, 2 as a main", user_id: 784, editors_pick: fals
e, editors_comments: "", label: "pasta_with_lemonparmesan_butt
er", flag_inappropriate: false, wine_id: nil, recipe_style: "a
b", varietal_id: nil, rating_average: 0, makes_serves: "Serves
", flag_inappropriate_comments: nil, sommelier_comments: nil,
comments_count: 1, is_winner: false, interest: 1, is_finalist:
nil, new_categories_added: nil, admin_categorization_note: nil
Luckily, there’s a super simple way to get some nicer formatting.
The Kernel module has a private instance method #y which will print out an active record object (or anything else) as YAML.
Check it out:
>> y User.find_by_login("Michael Hoffman").recipes.last
updated_at: 2012-08-29 16:20:58
serving_size: 4 as a pasta course, 2 as a main
title: Pasta with Lemon-Parmesan Butter
description: "I was walking by a little pizzeria in the East
Village - one I've never been to and may never go to - and
I slowed my gait to glance at the menu. My eyes happened t
o land on a pasta dish. I don't remember exactly what it w
as called, but it involved lemon and parmesan, and not muc
h else. Lemon! So obvious. Why had I never thought of that
? The next night I made this for dinner."
created_at: 2012-08-29 00:03:55
Notice that, in addition to producing more legible formatting, #y does not truncate values, so we get to see the whole description of the recipe.
Another great use case for this method is visualizing nested hashes and arrays.
Apparently this method relies on the Syck YAML parser.
For this reason, it won’t immediately work out of the box with Ruby 1.9.3, which uses the Psych parser by default.
If you’re using 1.9.3 and you want to play around with Kernel#y, run YAML::ENGINE.yamler = 'syck' to change parsers.
And a question: I’d like to know how to get #y to print out ActiveRecord attributes in the same order as they are normally displayed.
(By the way, I highly recommend trying out the recipe mentioned above.)