• Stars
    star
    1,522
  • Rank 30,777 (Top 0.7 %)
  • Language
    Ruby
  • License
    MIT License
  • Created almost 16 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Ruby ASCII Table Generator, simple and feature rich.

CI status Gem Version

Terminal Table

Description

Terminal Table is a fast and simple, yet feature rich table generator written in Ruby. It supports ASCII and Unicode formatted tables.

Installation

$ gem install terminal-table

Usage

Basics

To use Terminal Table:

require 'terminal-table'

To generate a table, provide an array of arrays (which are interpreted as rows):

rows = []
rows << ['One', 1]
rows << ['Two', 2]
rows << ['Three', 3]
table = Terminal::Table.new :rows => rows

# > puts table
#
# +-------+---+
# | One   | 1 |
# | Two   | 2 |
# | Three | 3 |
# +-------+---+

The constructor can also be given a block which is either yielded the Table object or instance evaluated:

table = Terminal::Table.new do |t|
  t.rows = rows
end

table = Terminal::Table.new do
  self.rows = rows
end

Adding rows one by one:

table = Terminal::Table.new do |t|
  t << ['One', 1]
  t.add_row ['Two', 2]
end

To add separators between rows:

table = Terminal::Table.new do |t|
  t << ['One', 1]          # Using << (push) as an alias for add_row
  t << :separator          # Using << with :separator as an alias for add_separator
  t.add_row ['Two', 2]
  t.add_separator          # Note - this version allows setting the separator's border_type
  t.add_row ['Three', 3]
end

# > puts table
#
# +-------+---+
# | One   | 1 |
# +-------+---+
# | Two   | 2 |
# +-------+---+
# | Three | 3 |
# +-------+---+

Cells can handle multiline content:

table = Terminal::Table.new do |t|
  t << ['One', 1]
  t << :separator
  t.add_row ["Two\nDouble", 2]
  t.add_separator
  t.add_row ['Three', 3]
end

# > puts table
#
# +--------+---+
# | One    | 1 |
# +--------+---+
# | Two    | 2 |
# | Double |   |
# +--------+---+
# | Three  | 3 |
# +--------+---+

Head

To add a head to the table:

table = Terminal::Table.new :headings => ['Word', 'Number'], :rows => rows

# > puts table
#
# +-------+--------+
# | Word  | Number |
# +-------+--------+
# | One   | 1      |
# | Two   | 2      |
# | Three | 3      |
# +-------+--------+

Title

To add a title to the table:

table = Terminal::Table.new :title => "Cheatsheet", :headings => ['Word', 'Number'], :rows => rows

# > puts table
#
# +---------------------+
# |     Cheatsheet      |
# +------------+--------+
# | Word       | Number |
# +------------+--------+
# | One        | 1      |
# | Two        | 2      |
# | Three      | 3      |
# +------------+--------+

Alignment

To align the second column to the right:

table.align_column(1, :right)

# > puts table
#
# +-------+--------+
# | Word  | Number |
# +-------+--------+
# | One   |      1 |
# | Two   |      2 |
# | Three |      3 |
# +-------+--------+

To align an individual cell, you specify the cell value in a hash along the alignment:

table << ["Four", {:value => 4.0, :alignment => :center}]

# > puts table
#
# +-------+--------+
# | Word  | Number |
# +-------+--------+
# | One   |      1 |
# | Two   |      2 |
# | Three |      3 |
# | Four  |  4.0   |
# +-------+--------+

Style

To specify style options:

table = Terminal::Table.new :headings => ['Word', 'Number'], :rows => rows, :style => {:width => 80}

# > puts table
#
# +--------------------------------------+---------------------------------------+
# | Word                                 | Number                                |
# +--------------------------------------+---------------------------------------+
# | One                                  | 1                                     |
# | Two                                  | 2                                     |
# | Three                                | 3                                     |
# +--------------------------------------+---------------------------------------+

And change styles on the fly:

table.style = {:width => 40, :padding_left => 3, :border_x => "=", :border_i => "x"}

# > puts table
#
# x======================================x
# |               Cheatsheet             |
# x====================x=================x
# |   Word             |   Number        |
# x====================x=================x
# |   One              |   1             |
# |   Two              |   2             |
# |   Three            |   3             |
# x====================x=================x

You can also use styles to add a separator after every row:

table = Terminal::Table.new do |t|
  t.add_row [1, 'One']
  t.add_row [2, 'Two']
  t.add_row [3, 'Three']
  t.style = {:all_separators => true}
end

# > puts table
#
# +---+-------+
# | 1 | One   |
# +---+-------+
# | 2 | Two   |
# +---+-------+
# | 3 | Three |
# +---+-------+

You can also use styles to disable top and bottom borders of the table.

table = Terminal::Table.new do |t|
  t.headings = ['id', 'name']
  t.rows = [[1, 'One'], [2, 'Two'], [3, 'Three']]
  t.style = { :border_top => false, :border_bottom => false }
end

# > puts table
# | id | name  |
# +----+-------+
# | 1  | One   |
# | 2  | Two   |
# | 3  | Three |

And also to disable left and right borders of the table.

table = Terminal::Table.new do |t|
  t.headings = ['id', 'name']
  t.rows = [[1, 'One'], [2, 'Two'], [3, 'Three']]
  t.style = { :border_left => false, :border_right => false }
end

# > puts table
# ----+-------
#  id | name
# ----+-------
#  1  | One
#  2  | Two
#  3  | Three
# ----+-------

To change the default style options:

Terminal::Table::Style.defaults = {:width => 80}

All Table objects created afterwards will inherit these defaults.

Constructor options and setter methods

Valid options for the constructor are :rows, :headings, :style and :title - and all options can also be set on the created table object by their setter method:

table = Terminal::Table.new
table.title = "Cheatsheet"
table.headings = ['Word', 'Number']
table.rows = rows
table.style = {:width => 40}

New Formatting

Unicode Table Borders

Support for Unicode 'box art' borders presented a challenge, as the original terminal-table only handled three border types: horizontal (x), vertical (y), and intersection (i). For proper box-art, it became necessary to enable different types of corners/edges for multiple intersection types.

For the sake of backward compatiblity, the previous interface is still supported, as this gem has been around a long time and making breaking changes would have been inconvenient. The new interface is required for any complex and/or Unicode style bordering. A few variations on border style are supported via some new classes and creation of additional classes (or modification of characters used in existing ones) will allow for customized border types.

The simplest way to use an alternate border is one of the following:

table.style = { :border => :unicode }
table.style = { :border => :unicode_round }
table.style = { :border => :unicode_thick_edge }

These are a convenience wrapper around setting border using an instance of a class that inherits from Table::Terminal::Border

table.style = { :border => Terminal::Table::UnicodeBorder.new() }
table.style = { :border => Terminal::Table::UnicodeRoundBorder.new() }
table.style = { :border => Terminal::Table::UnicodeThickEdgeBorder.new() }

If you define a custom class and wish to use the symbol shortcut, you must namespace within Terminal::Table and end your class name with Border.

Markdown Compatiblity

Per popular request, Markdown formatted tables can be generated by using the following border style:

table.style = { :border => :markdown }

Ascii Borders

Ascii borders are default, but can be explicitly set with:

table.style = { :border => :ascii }

Customizing Borders

Inside the UnicodeBorder class, there are definitions for a variety of corner/intersection and divider types.

@data = {
  nil => nil,
  nw: "β”Œ", nx: "─", n:  "┬", ne: "┐",
  yw: "β”‚",          y:  "β”‚", ye: "β”‚", 
  aw: "β•ž", ax: "═", ai: "β•ͺ", ae: "β•‘", ad: 'β•€', au: "╧", # double
  bw: "┝", bx: "━", bi: "β”Ώ", be: "β”₯", bd: 'β”―', bu: "β”·", # heavy/bold/thick
  w:  "β”œ", x:  "─", i:  "β”Ό", e:  "─", dn: "┬", up: "β”΄", # normal div
  sw: "β””", sx: "─", s:  "β”΄", se: "β”˜",
  # alternative dots/dashes
  x_dot4:  'β”ˆ', x_dot3:  'β”„', x_dash:  'β•Œ',
  bx_dot4: '┉', bx_dot3: 'β”…', bx_dash: '╍',
}

Note that many are defined as directional (:nw == north-west), others defined in terms of 'x' or 'y'. The border that separates headings (below each heading) is of type :double and is defined with a* entries. Alternate :heavy types that can be applied to separators can be defined with b* entries.

When defining a new set of borders, it's probably easiest to define a new class that inherits from UnicodeBorder and replaces the @data Hash. However, these elements can be these can be overridden by poking setting the Hash, should the need arise:

table.style = {border: :unicode}
table.style.border[:nw] = '*'  # Override the north-west corner of the table

Customizing row separators

Row-separators can now be customized in a variety of ways. The default separator's border_type is referred to as :div. Additional separator border types (e.g. :double, :heavy, :dash - see full list below) can be applied to separate the sections (e.g. header/footer/title).

The separator's border_type may be specified when a user-defined separator is added. Alternatively, borders may be adjusted after the table's rows are elaborated, but before the table is rendered.

Separator border_types can be adjusted to be heavy, use double-lines, and different dash/dot styles. The border type should be one of:

div dash dot3 dot4 
thick thick_dash thick_dot3 thick_dot4
heavy heavy_dash heavy_dot3 heavy_dot4
bold bold_dash bold_dot3 bold_dot4
double

To manually set the separator border_type, the add_separator method may be called.

add_separator(border_type: :heavy_dash)

Alternatively, if style: :all_separators is used at the table level, it may be necessary to elaborate the implicit Separator rows prior to rendering.

table = Terminal::Table.new do |t|
  t.add_row [1, 'One']
  t.add_row [2, 'Two']
  t.add_row [3, 'Three']
  t.style = {:all_separators => true}
end
rows = table.elaborate_rows
rows[2].border_type = :heavy # modify separator row: emphasize below title
puts table.render

Example: Displaying a small CSV spreadsheet

This example code demonstrates using Terminal-table and CSV to display a small spreadsheet.

#!/usr/bin/env ruby
require "csv"
require "terminal-table"
use_stdin = ARGV[0].nil? || (ARGV[0] == '-')
io_object = use_stdin ? $stdin : File.open(ARGV[0], 'r')
csv = CSV.new(io_object)
csv_array = csv.to_a
user_table = Terminal::Table.new do |v|
  v.style = { :border => :unicode_round } # >= v3.0.0
  v.title = "Some Title"
  v.headings = csv_array[0]
  v.rows = csv_array[1..-1]
end
puts user_table

See also examples/show_csv_table.rb in the source distribution.

More examples

For more examples, please see the examples directory included in the source distribution.

Author

TJ Holowaychuk [email protected]

Unicode table support by Ben Bowers https://github.com/nanobowers

More Repositories

1

commander.js

node.js command-line interfaces made easy
JavaScript
26,707
star
2

n

Node version management
Shell
18,855
star
3

git-extras

GIT utilities -- repo summary, repl, changelog population, author commit percentages and more
Shell
17,295
star
4

co

The ultimate generator based flow-control goodness for nodejs (supports thunks, promises, etc)
JavaScript
11,853
star
5

ejs

Embedded JavaScript templates for node
JavaScript
4,450
star
6

node-prune

Remove unnecessary files from node_modules (.md, .ts, ...)
Go
4,297
star
7

consolidate.js

Template engine consolidation library for node.js
JavaScript
3,476
star
8

frontend-boilerplate

webpack-react-redux-babel-autoprefixer-hmr-postcss-css-modules-rucksack-boilerplate (unmaintained, I don't use it anymore)
JavaScript
2,939
star
9

connect-redis

Redis session store for Connect
TypeScript
2,788
star
10

should.js

BDD style assertions for node.js -- test framework agnostic
JavaScript
2,757
star
11

luna

luna programming language - a small, elegant VM implemented in C
C
2,446
star
12

dox

JavaScript documentation generator for node using markdown and jsdoc
JavaScript
2,159
star
13

mmake

Modern Make
Go
1,717
star
14

node-migrate

Abstract migration framework for node
JavaScript
1,522
star
15

axon

message-oriented socket library for node.js heavily inspired by zeromq
JavaScript
1,495
star
16

react-enroute

React router with a small footprint for modern browsers
JavaScript
1,490
star
17

commander

The complete solution for Ruby command-line executables
Ruby
1,089
star
18

mon

mon(1) - Simple single-process process monitoring program written in C
C
1,065
star
19

reds

light-weight, insanely simple full text search module for node.js - backed by Redis
JavaScript
891
star
20

node-thunkify

Turn a regular node function into one which returns a thunk
JavaScript
858
star
21

robo

Simple Go / YAML-based task runner for the team.
Go
786
star
22

react-click-outside

ClickOutside component for React.
JavaScript
775
star
23

gobinaries

Golang binaries compiled on-demand for your system
Go
770
star
24

node-blocked

Check if the event loop is blocked
JavaScript
722
star
25

node-ratelimiter

Abstract rate limiter for nodejs
JavaScript
719
star
26

staticgen

Static website generator that lets you use HTTP servers and frameworks you already know
Go
712
star
27

histo

beautiful charts in the terminal for static or streaming data
C
697
star
28

serve

Simple command-line file / directory server built with connect - supports stylus, jade, etc
JavaScript
563
star
29

styl

Flexible and fast modular CSS preprocessor built on top of Rework
JavaScript
525
star
30

pomo

Ruby Pomodoro app for the command-line (time / task management)
Ruby
525
star
31

go-spin

Terminal spinner package for Golang
Go
521
star
32

mdconf

Markdown driven configuration!
JavaScript
507
star
33

node-growl

growl unobtrusive notification system for nodejs
JavaScript
484
star
34

watch

watch(1) periodically executes the given command - useful for auto-testing, auto-building, auto-anything
C
458
star
35

node-querystring

querystring parser for node and the browser - supporting nesting (used by Express, Connect, etc)
JavaScript
452
star
36

node-delegates

Nodejs method and accessor delegation utility
JavaScript
418
star
37

haml.js

Faster Haml JavaScript implementation for nodejs
JavaScript
409
star
38

triage

Interactive command-line GitHub issue & notification triaging tool.
Go
399
star
39

log.js

super light-weight nodejs logging + streaming log reader
HTML
368
star
40

go-tea

Tea provides an Elm inspired functional framework for interactive command-line programs.
Go
364
star
41

punt

Elegant UDP messaging for nodejs
JavaScript
341
star
42

react-fatigue-dev

Module of modules for making modules
Makefile
312
star
43

php-selector

PHP DOM parser / queries with CSS selectors
PHP
300
star
44

node-gify

Convert videos to gifs using ffmpeg and gifsicle
JavaScript
296
star
45

palette

Node.js image color palette extraction with node-canvas
JavaScript
292
star
46

better-assert

c-style assert() for nodejs, reporting the expression string as the error message
JavaScript
285
star
47

js-yaml

CommonJS YAML Parser -- fast, elegant and tiny yaml parser for javascript
JavaScript
275
star
48

go-naturaldate

Natural date/time parsing for Go.
Go
272
star
49

lingo

Linguistics module for Node - inflection, transformation, i18n and more
JavaScript
270
star
50

react-batch

Batch component for performant frequent updates (flush on count or interval)
JavaScript
251
star
51

sponsors-api

GitHub Sponsor avatar listings in your Readme.md
Go
244
star
52

mad

mad(1) is a markdown manual page viewer
Shell
244
star
53

d3-heatmap

D3 heatmap
JavaScript
243
star
54

go-update

Go package for auto-updating system-specific binaries via GitHub releases.
Go
241
star
55

callsite

node.js access to v8's "raw" CallSites -- useful for custom traces, c-style assertions, getting the line number in execution etc
JavaScript
239
star
56

bm

CLI bookmarks -- dropbox persisted bookmarks in your terminal - view screenshots in your browser
Shell
229
star
57

term-canvas

javascript canvas api for your terminal!
JavaScript
226
star
58

go-termd

Package termd provides terminal markdown rendering, with code block syntax highlighting support.
Go
224
star
59

parse-curl.js

Parse curl commands, returning an object representing the request.
JavaScript
217
star
60

go-progress

Another Go progress bar
Go
216
star
61

es

Go DSL for Elasticsearch queries
Go
206
star
62

co-prompt

sane terminal user-input for node.js using thunks / generators
JavaScript
192
star
63

node-cookie-signature

cookie signing
JavaScript
183
star
64

co-views

Higher-level template rendering for node.js using generators
JavaScript
175
star
65

d3-bar

D3 bar chart
JavaScript
173
star
66

node-only

return whitelisted properties of an object
JavaScript
170
star
67

ngen

nodejs project generator
JavaScript
168
star
68

react-hooks

Fire off actions in stateless components.
JavaScript
167
star
69

letterbox

Go program to batch-process letter-boxing of photographs.
Go
164
star
70

go-search

Search Godoc.org via the command-line.
Go
159
star
71

co-monk

MongoDB generator goodness for node.js
JavaScript
155
star
72

eson

Extended (pluggable) JSON for node - great for configuration files and JSON transformations
JavaScript
150
star
73

growl

Ruby growlnotify 'bindings' (unobtrusive notification system)
Ruby
146
star
74

go

Go packages
Go
140
star
75

d3-series

D3 line series chart used for error reporting on Apex Ping
JavaScript
139
star
76

node-amp

Abstract message protocol for nodejs
JavaScript
135
star
77

channel.js

Go-style channel implementation for JavaScript
JavaScript
135
star
78

burl

better curl(1) through augmentation
Shell
134
star
79

node-pwd

Hash and compare passwords with pbkdf2
JavaScript
132
star
80

jog

JSON document logging & filtering inspired by loggly for node.js
JavaScript
132
star
81

nedis

Redis server implementation written with nodejs
JavaScript
131
star
82

d3-circle

D3 circle chart
JavaScript
130
star
83

d3-dot

D3 dot chart
JavaScript
129
star
84

node-term-list

Interactive terminal list for nodejs
JavaScript
126
star
85

node-comment-macros

JavaScript comment macros useful for injecting logging, tracing, debugging, or stats related code.
JavaScript
126
star
86

d3-line

D3 line chart
JavaScript
125
star
87

asset

little asset manager for lazy people (think bundler/homebrew/npm for assets). written with node
JavaScript
122
star
88

go-dropbox

Dropbox v2 client for Go.
Go
120
star
89

node-term-css

style terminal output using CSS
JavaScript
116
star
90

go-terminput

Package terminput provides terminal keyboard input for interactive command-line tools.
Go
114
star
91

vscode-snippets

Personal VSCode snippets for Go, JS, Elm, etc.
114
star
92

nshell

scriptable command-line shell written with node.js
JavaScript
109
star
93

node-actorify

Turn any node.js duplex stream into an actor
JavaScript
108
star
94

co-parallel

Execute thunks in parallel with concurrency support
JavaScript
108
star
95

node-monquery

mongodb query language for humans
JavaScript
106
star
96

co-fs

nodejs core fs module thunk wrappers for "co"
JavaScript
105
star
97

axon-rpc

Axon RPC client / server
JavaScript
103
star
98

s3.js

S3 uploads from the browser.
JavaScript
100
star
99

spa

Tiny Single Page Application server for Go with `spa` command-line tool.
Go
94
star
100

d3-tipy

D3 tooltip
JavaScript
94
star