table_print - 1.0.0.rc3

Turn objects into nicely formatted columns for easy reading

TablePrint formats an object or array of objects into columns for easy reading. To do this, it assumes the objects in your array all respond to the same methods.

Installation

# Install as a standalone gem

Usage

# Outside rails

You should see something like this:

> 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

TablePrint tries to use sensible defaults to choose the columns to show. If you're inspecting ActiveRecord objects, it uses the ActiveRecord column names. You can customize the output to show fewer columns, or show other methods you've written on your model. Use symbols or strings to reference the columns.

# Maybe you store a user's hourly rate but you want to see their yearly income
tp User.limit(30), :include => :yearly_income, :except => :hourly_rate

# Maybe all you care about is their mailing info
tp User.limit(30), :address, 'city', 'state', :zip

If you're not using ActiveRecord, the TablePrint default is to show all the methods defined directly on your object (nothing from superclasses/mixins).

You can reference nested objects with the method chain required to reach them. Say you had some users who wrote books, and those books had photos.

> tp Author.limit(3), "name", "books.title", "books.photos.caption"
NAME              | BOOKS.TITLE       | BOOKS.PHOTOS.CAPTION
-------------------------------------------------------------------------
Michael Connelly  | The Fifth Witness | Susan was running, fast, away...
                  |                   | Along came a spider.
                  | Malcolm X         |
                  | Bossypants        | Yes! Yes! A thousand times ye...
                  |                   | Don't see many like you aroun...
Carrot Top        |                   |
Milton Greene     | How I Learned     | Once upon a time, I was a sma...
                  |                   | Lemons are yellow, limes are ...
                  |                   | Never as a woman her age. I l...
                  | Desperados        | Avast.
                  |                   | Giraffes lived a peaceful exi...

Column options

Pass options to individual columns through the options hash by using the display method as the hash key. Eg, if you wanted a skinny email column, set the width explicitly:

tp User.all, :email => {:width => 12}

Available column options:

  • display_method - string/symbol/proc - used to populate the column. Can be a method name or a proc. See below.

  • formatters - array of objects - each will be called in turn as the cells are printed. Must define a 'format' method. See below.

  • time_format - string - passed to strftime, only affects time columns

  • width - integer - how wide you want your column. Currently cannot exceed max_width.

Display method

Columns are named after hash keys. To rename a column, use the name you want as the key, and pass the method as an option.

tp User.all, :active => {:display_method => :active_in_the_past_six_months} # the User class defines active_in_the_past_six_months method

Lambdas

You can pass a proc as the display_method for a column:

tp User.all, :email, :monthly_payment, :yearly_payment => lambda{|u| u.monthly_payment * 12}

Or if you want to pass other options along with the lambda:

tp User.all, :yearly_payment => {:display_method => lambda{|u| u.monthly_payment * 12}, :width => 10}

Column formatters

Similar to a lambda column, you can use a column formatter to reuse code across prints. Any object with a 'format' method can be used to filter a column. This could also be used for coloring output.

class NoNewlineFormatter
  def format(value)
    value.to_s.gsub(/\r\n/, " ")
  end
end

tp User.all, :bio => {:formatters => [NoNewlineFormatter.new]} # strip newlines from user bios

Config

Use `tp.set` and `tp.clear` to set options on a class-by-class basis.

tp.set User, :id, :email # now whenever you print users, the only columns shown will be id and email

> tp User.first
ID | EMAIL
----------------
1  | foo@bar.com

# the config sets a 'baseline' for each print. You can still include/except columns:
> tp User.first, :except => :email
ID
--
17

# you can still provide a specific set of columns:
> tp User.first, :first_name
FIRST_NAME
----------
Phooey

tp.clear User # back to square one - print all the columns we can find

You can also set individual options:

tp.set :max_width, 10 # columns won't exceed 10 characters
tp.set :time_format, "%Y" # date columns will only show the year

Contributing to table_print

  • Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet

  • Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it

  • Fork the project

  • Start a feature/bugfix branch

  • Commit and push until you are happy with your contribution

  • Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.

  • Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.

Copyright

Copyright © 2012 Chris Doyle. See LICENSE.txt for further details.