Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/arches/table_print
The best data slicer! Watch a 3 minute screencast at http://tableprintgem.com
https://github.com/arches/table_print
Last synced: about 1 month ago
JSON representation
The best data slicer! Watch a 3 minute screencast at http://tableprintgem.com
- Host: GitHub
- URL: https://github.com/arches/table_print
- Owner: arches
- License: mit
- Created: 2011-04-10T17:20:44.000Z (over 13 years ago)
- Default Branch: master
- Last Pushed: 2023-03-21T03:55:03.000Z (over 1 year ago)
- Last Synced: 2024-05-17T16:14:38.502Z (7 months ago)
- Language: Ruby
- Homepage:
- Size: 398 KB
- Stars: 894
- Watchers: 19
- Forks: 45
- Open Issues: 30
-
Metadata Files:
- Readme: README.rdoc
- License: LICENSE.txt
Awesome Lists containing this project
- awesome-ruby-toolbox - table_print - TablePrint turns objects into nicely formatted columns for easy reading. Works great in rails console, works on pure ruby objects, autodetects columns, lets you traverse ActiveRecord associations. Simple, powerful. (Developer Tools / irb Tools)
- awesome-ruby - TablePrint - Slice your data from multiple DB tables into a single CLI view. (CLI Utilities)
README
= table_print
{}[http://travis-ci.org/arches/table_print]
{}[https://codeclimate.com/github/arches/table_print]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}[http://tableprintgem.com] will give you a quick overview of table_print's most
powerful features and how to use them.http://arches.io/tp_example.gif
== 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, optionsYou 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 | BossypantsTablePrint 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', :zipIf 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}}, :ageAvailable 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[http://www.ruby-doc.org/core-1.9.3/Time.html#method-i-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
endtp 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
tag. You can create a helper
method to send table_print output directly into yourtag: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 | [email protected]# 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
----------
Phooeytp.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
=== MultibyteUnfortunately, 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
Copyright (c) 2013 Chris Doyle. See LICENSE.txt for further details.