8

I'm looking for a clean and simple way to print in the Rails Console the contents of my 5 row database with 2 columns.

Any ideas? I Googled around but didn't find much.

Zack Shapiro
  • 6,648
  • 17
  • 83
  • 151

4 Answers4

18

I think you should first use the hirb gem which provides a very pleasant way to print your tables columns.

  1. Install hirb gem: gem install hirb
  2. Add this gem to your project's Gemfile: gem 'hirb'
  3. Go to your project's root folder and run Rails console: rails c
  4. Enable hirb in the console:

    require 'hirb'
    Hirb.enable
    

If you want to limit the number of rows to display, you can do:

Model.limit(n)

For instance:

User.limit(5)

You can also specify the fields that you want to display using select:

User.select("name, email").limit(5)
yesnik
  • 4,085
  • 2
  • 30
  • 25
Amokrane Chentir
  • 29,907
  • 37
  • 114
  • 158
  • 2
    After looking into `hirb`, I'd also recommend `wirble` and `awesome-print`. Related: http://iain.nl/customizing-irb-2010-edition – Nick Jun 01 '12 at 19:38
8

You can also checkout table_print, it'll work something like this:

$ gem install table_print
$ rails c
> require 'table_print'
> tp Book.all
AUTHOR            | SUMMARY                         | TITLE
-----------------------------------------------------------------------
Michael Connelly  | Another book by Michael Con...  | The Fifth Witness
Manning Mardale   | From acclaimed historian Ma...  | Malcolm X
Tina Fey          | Worth it. -Trees                | Bossypants
Chris Doyle
  • 1,029
  • 12
  • 15
2

With hirb:

require 'hirb'
puts Hirb::Helpers::Table.render(ARRAY_OF_OBJECT_OR_HASHES)

# Examples:

puts Hirb::Helpers::Table.render([[1, "Terminator I"], [2, "Terminator II"]])

+---+---------------+
| 0 | 1             |
+---+---------------+
| 1 | Terminator I  |
| 2 | Terminator II |
+---+---------------+

puts Hirb::Helpers::Table.render([{ id: 1, name: "Terminator I" }, { id: 2, name: "Terminator II" }])

+----+---------------+
| id | name          |
+----+---------------+
| 1  | Terminator I  |
| 2  | Terminator II |
+----+---------------+

# specifying the order of the fields
puts Hirb::Helpers::Table.render([{ id: 1, name: "Terminator I" }, { id: 2, name: "Terminator II" }], fields: [:name, :id])

+---------------+----+
| name          | id |
+---------------+----+
| Terminator I  | 1  |
| Terminator II | 2  |
+---------------+----+
Dorian
  • 22,759
  • 8
  • 120
  • 116
1

Yes. Check out hirb gem. Also worth trying is wirble and awesome_print.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
Hauleth
  • 22,873
  • 4
  • 61
  • 112