I want to get something like this to look nice:
>> ProductColor.all
=> [#
You should try hirb. It's a gem made to to pretty format objects in the ruby console. Your script/console session would look like this:
>> require 'hirb'
=> true
>> Hirb.enable
=> true
>> ProductColor.first
+----+-------+---------------+---------------------+---------------------+
| id | name | internal_name | created_at | updated_at |
+----+-------+---------------+---------------------+---------------------+
| 1 | White | White | 2009-06-10 04:02:44 | 2009-06-10 04:02:44 |
+----+-------+---------------+---------------------+---------------------+
1 row in set
=> true
You can learn more about hirb at its homepage.
Use irbtools
gem.
It will automatically format the the console output plus you'll get tons of great features.
I had some troubles making it work so I'll add my two cents to awesome_print
add this to your Gemfile, preferably in :development
gem 'awesome_print', require: 'ap'
then in
rails console
you can do
> ap Model.all
That's it. However you can also add
require "awesome_print"
AwesomePrint.irb!
to your ~/.irbrc, this way awesome_print will be required anytime you open the console and you can simply do
Model.all without the need of typing ap
You may also try the following for a group of objects
Object.all.map(&:attributes).to_yaml
This will give you much nicer output, like
---
id: 1
type: College
name: University of Texas
---
id: 2
type: College
name: University of California
Calling to_yaml
on attributes rather than the object itself saves you from viewing the full contents of the object in the output
Or puts Object.last.attributes.to_yaml
for a single object
Shorthand is also available: y Object.last.attributes
The y
method is a handy way to get some pretty YAML output.
y ProductColor.all
Assuming you are in script/console
As jordanpg commented, this answer is outdated. For Rails 3.2+ you need to execute the following code before you can get the y
method to work:
YAML::ENGINE.yamler = 'syck'
From ruby-docs
In older Ruby versions, ie. <= 1.9, Syck is still provided, however it was completely removed with the release of Ruby 2.0.0.
For rails 4/ruby 2 you could use just
puts object.to_yaml
>> puts ProductColor.all.to_yaml
Simply works fine!
Source: https://stackoverflow.com/a/4830096