Code Monkey home page Code Monkey logo

terminal-table's Introduction

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

terminal-table's People

Contributors

agentydragon avatar bobwhitelock avatar chewi avatar codegoalie avatar dduugg avatar erwanlr avatar gilesbowkett avatar greg-hellings avatar groguelon avatar jescholl avatar jrmhaig avatar juanitofatas avatar kubakrzempek avatar leoarnold avatar loualrid avatar mvz avatar nanobowers avatar nateberkopec avatar olleolleolle avatar petergoldstein avatar rrrene avatar scottjg avatar sephi-chan avatar smtlaissezfaire avatar splattael avatar tj avatar toy avatar viking avatar vizv avatar wbotelhos avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

terminal-table's Issues

Table Title

Hi, I read the documentation and tried to add a title to the table, but it kept throwing an undefined method title= exception. In the source on GitHub it seems to be implemented, but then i opened the latest gem I installed and noticed the Table class doesn't have that method yet.

Any chance you could release a new version of the gem containing this feature?

Cheers,
Michael

Cut a release

Hi, can you cut a release with the relaxed unicode-display_width dependency?
Thanks!

Consider tagging a new release

Hey, first: thanks for your work 😄

I would like to kindly ask for a new release... quote some time has passed and there are several projects that stick with the 1.4.5 version because of #59.
It would be really awesome if we can get a new release after nearly 1 year 😸

Crashes when used in a Signal trap (v 1.7.0)

This possibly isn't something that you want to fix, although there may a simple workaround, but by using the unicode-display_width gem Terminal Table can now not be used in a Signal trap. See janlelis/unicode-display_width#9

The simple workaround (I think) is to include:

require 'unicode/display_width/index'

somewhere in your code but the correct fix would be to set the minimum version of the unicode-display_width gem (to a version that has not yet been released).

Error if row height returns nil

Got this error
lib/terminal-table/row.rb:40:in `render': bad value for range (ArgumentError)

I think you can get this if table has no rows or values in row are nil

Quick fix that hepled me - ensure that height return int instead of nil:

module Terminal
  class Table
    class Row
      def height
        h = cells.map { |c| c.lines.count }.max
        h ? h : 0
      end
    end
  end
end

Monkeypatching "left" in String conflicts with Active Record

I recently had to track down a problem with a Rails application where a query was failing and isolated it to this code in Active Record:

counts = table_joins.map do |join|
  if join.is_a?(Arel::Nodes::StringJoin)
    # Table names + table aliases
    join.left.downcase.scan(
      /join(?:\s+\w+)?\s+(\S+\s+)?#{quoted_name}\son/
    ).size
  elsif join.respond_to? :left
    join.left.table_name == name ? 1 : 0
  else
    0
  end
end

Since terminal_table aliases String#ljust, to left, any instance of String responds to left when using this gem. In the example above this leads to an ArgumentError. This happens to me on Rails 4.0.12, but I've verified that similar code exists in Rails 4.2.0 as well. To reproduce, create a scope with a manual join, and then invoke the exists? method on the scope. For example:

class Foo < ActiveRecord::Base
  belongs_to :bar
  scope :baz, -> {joins('INNER JOIN bars on bars.id = foos.bar_id')}
end

Foo.baz.exists?(1)

I would suggest removing the aliases in String completely and using the ljust and rjust methods internally instead; left is a very generic method name to add to a core class like String and is likely to conflict with other libraries as well.

Rendering error for short ansi-colored lines

The error is reproduced in terminal-table v. 1.4.4.

Sample code

require 'term/ansicolor'
class String; include Term::ANSIColor; end

rows = []
rows << ['Some', 1]
rows << :separator
rows << ["Another word\n" + 'Sub2'.yellow, 2]
rows << :separator
rows << ["Three".red, 3]
puts(Terminal::Table.new :headings => ['W'.green, 'N'.green], :rows => rows)

Output:

+-------+---+
| W | N |
+-------+---+
| Some  | 1 |
+-------+---+
| Another word | 2 |
| Sub2 |   |
+-------+---+
| Three | 3 |
+-------+---+

My fix for this issue:

module Terminal
  class Table
    class Cell

      ##
      # Returns the longest line in the cell
      def value_for_column_width_recalc
        lines.map{ |s| escape(s) }.max_by{ |s| s.size }
      end


      def render(line = 0)
        left = " " * @table.style.padding_left
        right = " " * @table.style.padding_right
        render_width = lines[line].to_s.size - escape(lines[line]).size + width
        "#{left}#{lines[line]}#{right}".align(alignment, render_width + @table.cell_padding)
      end

      private

      ##
      # removes all ANSI escape sequences (e.g. color)      
      def escape(line)
        line.to_s.gsub(/\x1b(\[|\(|\))[;?0-9]*[0-9A-Za-z]/, '').
          gsub(/\x1b(\[|\(|\))[;?0-9]*[0-9A-Za-z]/, '').
          gsub(/[\x03|\x1a]/, '')
      end

    end
  end
end

That solves the problem.

Output:

+--------------+---+
| W            | N |
+--------------+---+
| Some         | 1 |
+--------------+---+
| Another word | 2 |
| Sub2         |   |
+--------------+---+
| Three        | 3 |
+--------------+---+

New Release?

It's been over a year since the last release was pushed out to Rubygems, and a lot of code has gone into terminal-table since then.

Any chance of pushing a new release? Thanks!

Syntax Error terminal-table/table.rb:252

terminal-table/table.rb:252: syntax error, unexpected tLPAREN_ARG
resolve = -> (colspan, full_width, index = 0) do

Ruby Version : 1.9.3
terminal-table version : 1.7.2

Thanks,
Khirod

Encoding utf-8

Terminal-table is incompatible character encodings: UTF-8 and ASCII-8BIT (Encoding::CompatibilityError)
I can't print á é í ó ú

Specifying a table width less than the combined column widths breaks

I set the width of a table to less than the width of all the columns combined and got this error:

undefined local variable or method `wanted' for #<Terminal::Table:0x007fd99a490248>
/Users/avand/Code/sqoot/api/vendor/ruby/1.9.1/gems/terminal-table-1.4.5/lib/terminal-table/table.rb:169:in `additional_column_widths'
/Users/avand/Code/sqoot/api/vendor/ruby/1.9.1/gems/terminal-table-1.4.5/lib/terminal-table/table.rb:85:in `column_width'
/Users/avand/Code/sqoot/api/vendor/ruby/1.9.1/gems/terminal-table-1.4.5/lib/terminal-table/separator.rb:7:in `block in render'
/Users/avand/Code/sqoot/api/vendor/ruby/1.9.1/gems/terminal-table-1.4.5/lib/terminal-table/separator.rb:6:in `map'
/Users/avand/Code/sqoot/api/vendor/ruby/1.9.1/gems/terminal-table-1.4.5/lib/terminal-table/separator.rb:6:in `render'
/Users/avand/Code/sqoot/api/vendor/ruby/1.9.1/gems/terminal-table-1.4.5/lib/terminal-table/table.rb:120:in `block in render'
/Users/avand/Code/sqoot/api/vendor/ruby/1.9.1/gems/terminal-table-1.4.5/lib/terminal-table/table.rb:120:in `map'
/Users/avand/Code/sqoot/api/vendor/ruby/1.9.1/gems/terminal-table-1.4.5/lib/terminal-table/table.rb:120:in `render'

Looks like the exception references a non-existent variable. Should be a pretty easy fix.

Can we add a separator per cell?

Hello there,
Is there a way to add a separator per cell?

example (notice host1's tcp and udp protocols)

# +------------+-----------+-------+
# |           Cheatsheet           |        
# +------------+-----------+-------+
# | Host       | Protocols | Ports |
# +------------+-----------+-------+
# | host1      | tcp       | 80    |
# |            |           | 443   |
# |            |           | 445   |
# |            +-----------+-------+
# |            | udp       | 21    |
# |            |           | 22    |
# |            |           | 23    |
# |            |           | 24    |
# +------------+-----------+-------+
# | host2      | tcp       | 123   |
# +------------+-----------+-------+
# | host3      | udb       | 123   |
# +------------+-----------+-------+

Feature: set column max width (or automatically truncate input)

Hello,

I really appreciate what you did here! I was wondering if/when you are planning to add an optional max width for a column, with some kind of word wrap, or even just respecting newlines in a string and looking at the longest line only.

Thanks!

Christoph

Can we use this to create 2d tables?

I want to create a 2d table in the below format
Vitamin | Apple | Mango | Banana
A|
B|
C|
Where the above mentioned fields are the rows and columns and i need to fill data into this table.

Streaming output

I'm happy to set the width in advance, but I don't want to wait for my script to finish before I can print the table, that kind of ruins it :(

terminal-table 1.4.5 has spec failures

With ruby 1.9.3p429 (2013-05-15 revision 40747) [x86_64-linux] I'm seeing these failures:

  1) Terminal::Table should account for the colspan when selecting columns
     Failure/Error: @table.column_with_headings(1).should == [2,"4,5"]
       expected: [2, "4,5"]
            got: [2, 6] (using ==)
     # ./spec/table_spec.rb:31:in `block (2 levels) in <module:Terminal>'

  2) Terminal::Table should only increase column size for multi-column if it is unavoidable
     Failure/Error: EOF
       expected: "+-------+---+---+\n| 12345 | 2 | 3 |\n| 123456789 | 4 |\n+-------+---+---+"
            got: "+-------+-----+---+\n| 12345 | 2   | 3 |\n| 123456789   | 4 |\n+-------+-----+---+" (using ==)
       Diff:
       @@ -1,5 +1,5 @@
       -+-------+---+---+
       -| 12345 | 2 | 3 |
       -| 123456789 | 4 |
       -+-------+---+---+
       ++-------+-----+---+
       +| 12345 | 2   | 3 |
       +| 123456789   | 4 |
       ++-------+-----+---+
     # ./spec/table_spec.rb:429:in `block (2 levels) in <module:Terminal>'

Output layout is broken by multibyte character

Output layout is broken by multibyte character

Hi, all

Thank you for providing this software. I love to use this.
And I have a feature request for multibyte character.

When I input a context which has multibyte character as below,

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

puts table

the separation character of | is shifted like following.

+-----+---+
| One | 1 |
| Two | 2 |
+-----+---+

Help with table style

Hi, could someone help me produce a table that looks like this?

   |  1  2  3
---+---------
 1 |  1  2  3
 2 |  2  4  6

I can't figure out the styling from the docs.

Thanks

:colspan creates conflicts with colorize

(Say that title ten times fast...)

Using terminal-table has been fantastic for me, particularly due to its compatibility with colorize. I even combine colors with :border_x, :border_y and :border_i to create custom-colored tables/borders.

However I got around to experimenting with :colspan to split the display of "cell" data, and colorize ends up breaking :border_y.

table_sc

The tables turn out as such:

table_result

Of course, I can remove the :border_y styling to fix it...

table_result2

...but then I don't have my schnazzy blue dividers.

Capy-pasta-able code, in case you'd like to experiment:

require 'colorize'
require 'terminal-table'

original_sample_data = [
["Sep 2016", 33, [-38, -53.52], 46, [-25, -35.21]],
["Oct 2016", 35, [2, 6.06], 50, [4, 8.69]]
]

table = Terminal::Table.new headings: ["Month".cyan,"Monthly IT".cyan,"IT Difference OPM".cyan,
"Monthly OOT".cyan,"OOT Difference OPM".cyan], rows: original_sample_data

table.style = { padding_left: 2, padding_right: 2, border_x: "-".blue, border_y: "|".blue, border_i: "+".blue }

puts table

puts ""
puts "^ good table"
puts "v wonky talbe"
puts ""

split_column_sample_data = [
["Sep 2016", 33, -38, -53.52, 46, -25, -35.21],
["Oct 2016", 35, 2, 6.06, 50, 4, 8.69]
]

table = Terminal::Table.new headings: ["Month".cyan,"Monthly IT".cyan,
{value: "IT Difference OPM".cyan, colspan: 2}, "Monthly OOT".cyan,
{value: "OOT Difference OPM".cyan, colspan: 2}], rows: split_column_sample_data

table.style = { padding_left: 2, padding_right: 2, border_x: "-".blue, border_y: "|".blue, border_i: "+".blue }

puts table

undefined method `cells' for #<Array:0x007f8ba99466f0>

Hi,

We're getting the undefined method cells' for #Array:0x007f8ba99466f0` error in WPScan with terminal-table 1.5.2.

Full stack trace:

[!] undefined method `cells' for #<Array:0x007f902bd9c0e8>
[!] Trace:
[!] /Users/ryan/Tools/wpscan/lib/common/hacks.rb:69:in `render'
/Users/ryan/Tools/wpscan/lib/common/collections/wp_users/output.rb:25:in `output'
./wpscan.rb:364:in `main'
./wpscan.rb:443:in `<main>'

To reproduce:
/wpscan.rb -u www.somewordpresssite.com -w password-list.txt

Being tracked here by our users - wpscanteam/wpscan#841

Setting title breaks first column width

Setting the table title incorrectly changes the first column's width:

require 'rubygems'
require 'terminal-table'

table = Terminal::Table.new do |t|
  t.title = "This is a title"
  t.headings = %w{foo bar baz}
  t << %w{foo bar baz}
end
puts table

table = Terminal::Table.new do |t|
  t.headings = %w{foo bar baz}
  t << %w{foo bar baz}
end
puts table

Output:

+-----------------+-----+-----+
|       This is a title       |
+-----------------+-----+-----+
| foo             | bar | baz |
+-----------------+-----+-----+
| foo             | bar | baz |
+-----------------+-----+-----+
+-----+-----+-----+
| foo | bar | baz |
+-----+-----+-----+
| foo | bar | baz |
+-----+-----+-----+

[Feature Request] Allow table to be padded with a row of empty cells

The feature I have in mind would improve readability when all_separators is false.

  • padding_top is available only if a title row exists.
  • padding_bottom is available either ways.

To illustrate:

Without table-padding (Current)

+------------+-------------+-----------+
| First Name | Middle Name | Last Name |
+------------+-------------+-----------+
| John       | Malkov      | Stuart    |
| Jane       | Roberta     | Phillips  |
| Chris      | Malcom      | Little    |
| Amy        | Jack        | Robinson  |
+------------+-------------+-----------+

With new table-padding: (Style 1)

+------------+-------------+-----------+
| First Name | Middle Name | Last Name |
+------------+-------------+-----------+
|            |             |           |
| John       | Malkov      | Stuart    |
| Jane       | Roberta     | Phillips  |
| Chris      | Malcom      | Little    |
| Amy        | Jack        | Robinson  |
+------------+-------------+-----------+
+------------+-------------+-----------+
| John       | Malkov      | Stuart    |
| Jane       | Roberta     | Phillips  |
| Chris      | Malcom      | Little    |
| Amy        | Jack        | Robinson  |
+------------+-------------+-----------+

With new table-padding: (Style 2)

+------------+-------------+-----------+
| First Name | Middle Name | Last Name |
+------------+-------------+-----------+
|            |             |           |
| John       | Malkov      | Stuart    |
| Jane       | Roberta     | Phillips  |
| Chris      | Malcom      | Little    |
| Amy        | Jack        | Robinson  |
|            |             |           |
+------------+-------------+-----------+
+------------+-------------+-----------+
| John       | Malkov      | Stuart    |
| Jane       | Roberta     | Phillips  |
| Chris      | Malcom      | Little    |
| Amy        | Jack        | Robinson  |
|            |             |           |
+------------+-------------+-----------+

Use nice UTF box-drawing characters for borders by default

Instead of boring ASCII characters:

+------+----------------------------------------------------+---------+---------+--------+
|   id | name                                               |         |         |        |
+------+----------------------------------------------------+---------+---------+--------+

is there a reason we don't use the nice UTF box-drawing characters by default?

That is, something more like this:

╒══════╤════════════════════════════════════════════════════╤═════════╤═════════╤════════╕
│   id │ name                                               │         │         │        │
╘══════╧════════════════════════════════════════════════════╧═════════╧═════════╧════════╛

Or if we can't make them the default for some reason, could we at least make it possible to use them for all corners and intersections?

Different intersections require different glyphs, so this doesn't look super great:

table.style = {border_x: '═', border_i: '╪', border_y: '│'}    
╪══════╪════════════════════════════════════════════════════╪═════════╪═════════╪════════╪
│   id │ name                                               │         │         │        │
╪══════╪════════════════════════════════════════════════════╪═════════╪═════════╪════════╪

The best-looking approximation I've come up with is:

table.style = {border_x: '═', border_i: '═', border_y: '│'}    
══════════════════════════════════════════════════════════════════════════════════════════
│   id │ name                                               │         │         │        │
══════════════════════════════════════════════════════════════════════════════════════════

is there a way to display rows from a SQL talble?

I'm trying to use terminal-table to display rows from SQL tables (for ex using "pg" gem), where you'll have multiple columns, and don't need a heading on the row.


| col1 | col2 | col3 | coln... |
| val1 | val2 | val3 | valn... |
| val1 | val2 | val3 | valn... |
| val1 | val2 | val3 | valn... |

The result is a hash, so I can do result.keys and then feed it to terminal-table like :headings => row.keys. But for rows :rows => row.values will fail with NoMethodError: undefined method `each' for "4196505504":String.

So, basically, it would need a switch to turn off the expectation of the row to be pairs of keys and values, and just print the whole row array in a line.

How to align headings?

Table data rows have align_column, which works great, but how do I align the heading of a table?
I usually want to right-align numbers, but the heading would look better if it's also aligned the same.

Row Titles?

I appreciate that I could add a new element at the front of my array, but is there a way to get Row Titles instead?

Thanks,
Hat

chinese support

When I use it to show Chinese table ,the cell alignment become not so beautiful。
image

Feature Request: Define width of each column

Thanks for writing this excellent gem.
I have a feature request. It would be great to have an option of defining width for each column. For instance, in your example column "word" could be 50 and column "Number" could be 10.

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

Very confusing project description

Hello,

when doing an internet search for "ASCII table", one will get an overwhelming amount of links to "ASCII table"s, which, predominantly, are about an ASCII encoding table (which is something entirely different from this project!).

I originally started by doing an Ubuntu package search:
apt-cache search ASCII

Within these results, I then searched for "table", and ended up locating various packages which said "ASCII tables", and this (seemingly this upstream project) package ruby-terminal-table which said:

ruby-terminal-table - ascii table generation library

So, there are two issues:

  • skipping the helpful clarification that this is about generating ASCII-based tables rather than "ASCII tables"
  • use of singular instead of plural (which would successfully hint at the actual purpose of this project, by other means)

Thus, I would suggest changing relevant descriptions
from "ascii table"
to "ascii-based tables"
, thus fully clarifying it by mentioning both based on and plural.

Within such a change, it might also be useful to correct (arguably) incorrect "ascii" spelling into the proper spec-compliant naming "ASCII", too.

Thanks!

colspan causes align_column to fail

> t = Terminal::Table.new(rows: [['name',{value:'values',colspan:2}],['test',1,2]]);
> t.align_column(2,:right)

NoMethodError: undefined method `alignment?' for nil:NilClass
from /Users/dbell/.rvm/gems/ruby-1.9.3-p429@cater/gems/terminal-table-1.4.5/lib/terminal-table/table.rb:27:in `block in align_column'
  /Users/dbell/.rvm/gems/ruby-1.9.3-p429@cater/gems/terminal-table-1.4.5/lib/terminal-table/table.rb:25:in `each'
  /Users/dbell/.rvm/gems/ruby-1.9.3-p429@cater/gems/terminal-table-1.4.5/lib/terminal-table/table.rb:25:in `each_with_index'
  /Users/dbell/.rvm/gems/ruby-1.9.3-p429@cater/gems/terminal-table-1.4.5/lib/terminal-table/table.rb:25:in `align_column'

[Feature Request] border_left and border_right style

Could you add the possibility of disabling the left and right borders of the table?

For example:

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

error aligning by default?

I am trying to align all my tables :right by default, since they deal mostly with numbers (integer and float).

Terminal::Style.defaults = {:alignment => :right} # fails with: uninitialized constant Terminal::Style

sttab = Terminal::Table.new :alignment => :right #NoMethodError: undefined method `alignment=' for #Terminal::Table::Style:0x8fe858c

Terminal::Table::Style.defaults = {:alignment => :right} # silently accepts, but later at new or initialize gives NoMethodError: undefined method `alignment=' for #Terminal::Table::Style:0x8498f38

ruby -v
ruby 1.9.2p290 (2011-07-09 revision 32553) [i686-linux]

terminal-table (1.4.5)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.