Skip to content

arches/table_print

Repository files navigation

table_print

<img src=“https://travis-ci.org/arches/table_print.svg?branch=master” /> <img src=“https://codeclimate.com/github/arches/table_print.png” />

TablePrint shows objects in nicely formatted columns for easy reading. It even lets you nest other tables of related objects, contextualizing data across tables. It’s incredibly flexible, yet simple, making it easy to see exactly the data you care about.

This three minute screencast will give you a quick overview of table_print’s most powerful features and how to use them.

Installation

# Install as a standalone gem
$ gem install table_print

# Or install within rails
In your Gemfile: gem "table_print"
$ bundle install

Usage

# Outside rails
$ irb
> require 'table_print'
> tp array_of_objects, options

# Inside rails, the gem has already been required by your Gemfile so all you need to do is
$ rails c
> tp array_of_objects, options

You should see something like this:

> tp Book.all
AUTHOR            | SUMMARY                         | TITLE
------------------|---------------------------------|------------------
Michael Connelly  | Another book by Michael Con...  | The Fifth Witness
Manning Marable   | 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}
tp User.all, :id, {:email => {:width => 12}}, :age

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.

  • display_name - string - useful if you want spaces in your column name

  • separator - string - default is vertical bar for console and markdown, change it to a comma for CSV output

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}

Make sure to add curly braces if you have more than one column with a lambda or if this column isn’t the last one.

tp User.all, :email, { daily_payment: lambda { |u| u.monthly_payment / 30} }, :monthly_payment, { yearly_payment: lambda { |u| u.monthly_payment * 12} }

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

HTML Output

Currently the best way to show table_print output on an HTML page is using a <pre> tag. You can create a helper method to send table_print output directly into your <pre> tag:

def tp_pre data, options={}
  content_tag :pre, TablePrint::Printer.new(data, options).table_print
end

CSV Output

Set the column separator to get an output you can save as a CSV:

tp.set :separator, ","

Since your CSV viewer probably already handles column widths for you, setting max_width to something very large will help you export your full data set. Otherwise, this CSV output will still be truncated to the default max_width of 30 characters.

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

# a specific set of columns will entirely override the baseline config:
> tp User.first, :first_name
FIRST_NAME
----------
Phooey

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

To see the config for a given object, use tp.config_for.

> tp.set User, :id, :email
> tp.config_for User
[:id, :email]

You can also set global options:

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

You can redirect output:

f = File.open("users.txt", "w")
tp.set :io, f
tp User.all # written to users.txt instead of STDOUT
tp.clear :io
tp User.all # writing to STDOUT again

Multibyte

Unfortunately, the current approach to finding the width of multibyte strings is too slow. If you’re going to be working with a lot of multibyte characters, set the multibyte option first to enable the slower yet more precise width calculation:

> tp.set :multibyte, true

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 © 2013 Chris Doyle. See LICENSE.txt for further details.