terminal-table-4.0.0/ 0000755 0000041 0000041 00000000000 14753020547 014452 5 ustar www-data www-data terminal-table-4.0.0/.gitignore 0000644 0000041 0000041 00000000113 14753020547 016435 0 ustar www-data www-data .DS_Store
pkg
tmp
*.cache
doc
vendor
/.bundle
Gemfile.lock
# tempfiles
*~
terminal-table-4.0.0/terminal-table.gemspec 0000644 0000041 0000041 00000001701 14753020547 020716 0 ustar www-data www-data # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'terminal-table/version'
Gem::Specification.new do |spec|
spec.name = "terminal-table"
spec.version = Terminal::Table::VERSION
spec.authors = ["TJ Holowaychuk", "Scott J. Goldman"]
spec.email = ["tj@vision-media.ca"]
spec.summary = "Simple, feature rich ascii table generation library"
spec.homepage = "https://github.com/tj/terminal-table"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 2"
spec.add_development_dependency "rake", "~> 13.0"
spec.add_development_dependency "rspec", ">= 3.0"
spec.add_development_dependency "pry"
spec.add_runtime_dependency "unicode-display_width", [">= 1.1.1", "< 4"]
end
terminal-table-4.0.0/.github/ 0000755 0000041 0000041 00000000000 14753020547 016012 5 ustar www-data www-data terminal-table-4.0.0/.github/dependabot.yml 0000644 0000041 0000041 00000000166 14753020547 020645 0 ustar www-data www-data version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
terminal-table-4.0.0/.github/workflows/ 0000755 0000041 0000041 00000000000 14753020547 020047 5 ustar www-data www-data terminal-table-4.0.0/.github/workflows/ci.yml 0000644 0000041 0000041 00000001121 14753020547 021160 0 ustar www-data www-data name: CI
on: [push, pull_request, workflow_dispatch]
jobs:
test:
if: "!contains(github.event.head_commit.message, 'ci skip')"
continue-on-error: ${{ endsWith(matrix.ruby, 'head') || matrix.ruby == 'debug' }}
strategy:
fail-fast: false
matrix:
os: [ubuntu]
ruby: [2.4, 2.5, 2.6, 2.7, '3.0', 3.1, 3.2, 3.3, 3.4]
runs-on: ${{ matrix.os }}-latest
steps:
- uses: actions/checkout@v4
- uses: ruby/setup-ruby@v1
with:
bundler-cache: true
ruby-version: ${{ matrix.ruby }}
- run: bundle exec rspec
terminal-table-4.0.0/lib/ 0000755 0000041 0000041 00000000000 14753020547 015220 5 ustar www-data www-data terminal-table-4.0.0/lib/terminal-table/ 0000755 0000041 0000041 00000000000 14753020547 020120 5 ustar www-data www-data terminal-table-4.0.0/lib/terminal-table/row.rb 0000644 0000041 0000041 00000003055 14753020547 021257 0 ustar www-data www-data module Terminal
class Table
class Row
##
# Row cells
attr_reader :cells
attr_reader :table
##
# Initialize with _width_ and _options_.
def initialize table, array = [], **_kwargs
@cell_index = 0
@table = table
@cells = []
array.each { |item| self << item }
end
def add_cell item
options = item.is_a?(Hash) ? item : {:value => item}
cell = Cell.new(options.merge(:index => @cell_index, :table => @table))
@cell_index += cell.colspan
@cells << cell
end
alias << add_cell
def [] index
cells[index]
end
def height
cells.map { |c| c.lines.count }.max || 0
end
def render
vleft, vcenter, vright = @table.style.vertical
(0...height).to_a.map do |line|
vleft + cells.map do |cell|
cell.render(line)
end.join(vcenter) + vright
end.join("\n")
end
def number_of_columns
@cells.collect(&:colspan).inject(0, &:+)
end
# used to find indices where we have table '+' crossings.
# in cases where the colspan > 1, then we will skip over some numbers
# if colspan is always 1, then the list should be incrementing by 1.
#
# skip 0 entry, because it's the left side.
# skip last entry, because it's the right side.
# we only care about "+/T" style crossings.
def crossings
idx = 0
@cells[0...-1].map { |c| idx += c.colspan }
end
end
end
end
terminal-table-4.0.0/lib/terminal-table/util.rb 0000644 0000041 0000041 00000000534 14753020547 021424 0 ustar www-data www-data module Terminal
class Table
module Util
# removes all ANSI escape sequences (e.g. color)
def ansi_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
module_function :ansi_escape
end
end
end
terminal-table-4.0.0/lib/terminal-table/import.rb 0000644 0000041 0000041 00000000207 14753020547 021756 0 ustar www-data www-data require 'terminal-table' #required as some people require this file directly from their Gemfiles
include Terminal::Table::TableHelper
terminal-table-4.0.0/lib/terminal-table/cell.rb 0000644 0000041 0000041 00000004751 14753020547 021373 0 ustar www-data www-data require 'unicode/display_width'
module Terminal
class Table
class Cell
##
# Cell value.
attr_reader :value
##
# Column span.
attr_reader :colspan
##
# Initialize with _options_.
def initialize options = nil
@value, options = options, {} unless Hash === options
@value = options.fetch :value, value
@alignment = options.fetch :alignment, nil
@colspan = options.fetch :colspan, 1
@width = options.fetch :width, @value.to_s.size
@index = options.fetch :index
@table = options.fetch :table
end
def alignment?
!@alignment.nil?
end
def alignment
@alignment || @table.style.alignment || :left
end
def alignment=(val)
supported = %w(left center right)
if supported.include?(val.to_s)
@alignment = val
else
raise "Aligment must be one of: #{supported.join(' ')}"
end
end
def align(val, position, length)
positions = { :left => :ljust, :right => :rjust, :center => :center }
val.public_send(positions[position], length)
end
def lines
@value.to_s.encode("utf-8", invalid: :replace).split(/\n/)
end
##
# Render the cell.
def render(line = 0)
left = " " * @table.style.padding_left
right = " " * @table.style.padding_right
display_width = Unicode::DisplayWidth.of(Util::ansi_escape(lines[line]))
render_width = lines[line].to_s.size - display_width + width
align("#{left}#{lines[line]}#{right}", alignment, render_width + @table.cell_padding)
end
alias :to_s :render
##
# Returns the longest line in the cell and
# removes all ANSI escape sequences (e.g. color)
def value_for_column_width_recalc
lines.map{ |s| Util::ansi_escape(s) }.max_by{ |s| Unicode::DisplayWidth.of(s) }
end
##
# Returns the width of this cell
def width
padding = (colspan - 1) * @table.cell_spacing
inner_width = (1..@colspan).to_a.inject(0) do |w, counter|
w + @table.column_width(@index + counter - 1)
end
inner_width + padding
end
def inspect
fields = %i[alignment colspan index value width].map do |name|
val = self.instance_variable_get('@'+name.to_s)
"@#{name}=#{val.inspect}"
end.join(', ')
return "#<#{self.class} #{fields}>"
end
end
end
end
terminal-table-4.0.0/lib/terminal-table/separator.rb 0000644 0000041 0000041 00000004532 14753020547 022451 0 ustar www-data www-data module Terminal
class Table
class Separator < Row
##
# `prevrow`, `nextrow` contain references to adjacent rows.
#
# `border_type` is a symbol used to control which type of border is used
# on the separator (:top for top-edge, :bot for bottom-edge,
# :div for interior, and :strong for emphasized-interior)
#
# `implicit` is false for user-added separators, and true for
# implicit/auto-generated separators.
def initialize(*args, border_type: :div, implicit: false)
super
@prevrow, @nextrow = nil, nil
@border_type = border_type
@implicit = implicit
end
attr_accessor :border_type
attr_reader :implicit
def render
left_edge, ctrflat, ctrud, right_edge, ctrdn, ctrup = @table.style.horizontal(border_type)
prev_crossings = @prevrow.respond_to?(:crossings) ? @prevrow.crossings : []
next_crossings = @nextrow.respond_to?(:crossings) ? @nextrow.crossings : []
rval = [left_edge]
numcols = @table.number_of_columns
(0...numcols).each do |idx|
rval << ctrflat * (@table.column_width(idx) + @table.cell_padding)
pcinc = prev_crossings.include?(idx+1)
ncinc = next_crossings.include?(idx+1)
border_center = if pcinc && ncinc
ctrud
elsif pcinc
ctrup
elsif ncinc
ctrdn
elsif !ctrud.empty?
# special case if the center-up-down intersection is empty
# which happens when verticals/intersections are removed. in that case
# we do not want to replace with a flat element so return empty-string in else block
ctrflat
else
''
end
rval << border_center if idx < numcols-1
end
rval << right_edge
rval.join
end
# Save off neighboring rows, so that we can use them later in determining
# which types of table edges to use.
def save_adjacent_rows(prevrow, nextrow)
@prevrow = prevrow
@nextrow = nextrow
end
end
end
end
terminal-table-4.0.0/lib/terminal-table/table.rb 0000644 0000041 0000041 00000025100 14753020547 021532 0 ustar www-data www-data require 'unicode/display_width'
module Terminal
class Table
attr_reader :title
attr_reader :headings
##
# Generates a ASCII/Unicode table with the given _options_.
def initialize options = {}, &block
@elaborated = false
@headings = []
@rows = []
@column_widths = []
self.style = options.fetch :style, {}
self.headings = options.fetch :headings, []
self.rows = options.fetch :rows, []
self.title = options.fetch :title, nil
yield_or_eval(&block) if block
style.on_change(:width) { require_column_widths_recalc }
end
##
# Align column _n_ to the given _alignment_ of :center, :left, or :right.
def align_column n, alignment
# nil forces the column method to return the cell itself
column(n, nil).each do |cell|
cell.alignment = alignment unless cell.alignment?
end
end
##
# Add a row.
def add_row array
row = array == :separator ? Separator.new(self) : Row.new(self, array)
@rows << row
require_column_widths_recalc unless row.is_a?(Separator)
end
alias :<< :add_row
##
# Add a separator.
def add_separator(border_type: :div)
@rows << Separator.new(self, border_type: border_type)
end
def cell_spacing
cell_padding + style.border_y_width
end
def cell_padding
style.padding_left + style.padding_right
end
##
# Return column _n_.
def column n, method = :value, array = rows
array.map { |row|
# for each cells in a row, find the column with index
# just greater than the required one, and go back one.
index = col = 0
row.cells.each do |cell|
break if index > n
index += cell.colspan
col += 1
end
cell = row[col - 1]
cell && method ? cell.__send__(method) : cell
}.compact
end
##
# Return _n_ column including headings.
def column_with_headings n, method = :value
column n, method, headings_with_rows
end
##
# Return columns.
def columns
(0...number_of_columns).map { |n| column n }
end
##
# Return length of column _n_.
def column_width n
column_widths[n] || 0
end
alias length_of_column column_width # for legacy support
##
# Return total number of columns available.
def number_of_columns
headings_with_rows.map { |r| r.number_of_columns }.max || 0
end
##
# Set the headings
def headings= arrays
return if arrays.nil?
arrays = [arrays] unless arrays.first.is_a?(Array)
@headings = arrays.map do |array|
row = Row.new(self, array)
require_column_widths_recalc
row
end
end
##
# Elaborate rows to form an Array of Rows and Separators with adjacency properties added.
#
# This is separated from the String rendering so that certain features may be tweaked
# before the String is built.
def elaborate_rows
buffer = style.border_top ? [Separator.new(self, border_type: :top, implicit: true)] : []
unless @title.nil?
buffer << Row.new(self, [title_cell_options])
buffer << Separator.new(self, implicit: true)
end
@headings.each do |row|
unless row.cells.empty?
buffer << row
buffer << Separator.new(self, border_type: :double, implicit: true)
end
end
if style.all_separators
@rows.each_with_index do |row, idx|
# last separator is bottom, others are :div
border_type = (idx == @rows.size - 1) ? :bot : :div
buffer << row
buffer << Separator.new(self, border_type: border_type, implicit: true)
end
else
buffer += @rows
buffer << Separator.new(self, border_type: :bot, implicit: true) if style.border_bottom
end
# After all implicit Separators are inserted we need to save off the
# adjacent rows so that we can decide what type of intersections to use
# based on column spans in the adjacent row(s).
buffer.each_with_index do |r, idx|
if r.is_a?(Separator)
prev_row = idx > 0 ? buffer[idx - 1] : nil
next_row = buffer.fetch(idx + 1, nil)
r.save_adjacent_rows(prev_row, next_row)
end
end
@elaborated = true
@rows = buffer
end
##
# Render the table.
def render
elaborate_rows unless @elaborated
@rows.map { |r| style.margin_left + r.render.rstrip }.join("\n")
end
alias :to_s :render
##
# Return rows without separator rows.
def rows
@rows.reject { |row| row.is_a? Separator }
end
def rows= array
@rows = []
array.each { |arr| self << arr }
end
def style=(options)
style.apply options
end
def style
@style ||= Style.new
end
def title=(title)
@title = title
require_column_widths_recalc
end
##
# Check if _other_ is equal to self. _other_ is considered equal
# if it contains the same headings and rows.
def == other
if other.respond_to? :render and other.respond_to? :rows
self.headings == other.headings and self.rows == other.rows
end
end
private
def columns_width
column_widths.inject(0) { |s, i| s + i + cell_spacing } + style.border_y_width
end
def recalc_column_widths
@require_column_widths_recalc = false
n_cols = number_of_columns
space_width = cell_spacing
return if n_cols == 0
# prepare rows
all_rows = headings_with_rows
all_rows << Row.new(self, [title_cell_options]) unless @title.nil?
# DP states, dp[colspan][index][split_offset] => column_width.
dp = []
# prepare initial value for DP.
all_rows.each do |row|
index = 0
row.cells.each do |cell|
cell_value = cell.value_for_column_width_recalc
cell_width = Unicode::DisplayWidth.of(cell_value.to_s)
colspan = cell.colspan
# find column width from each single cell.
dp[colspan] ||= []
dp[colspan][index] ||= [0] # add a fake cell with length 0.
dp[colspan][index][colspan] ||= 0 # initialize column length to 0.
# the last index `colspan` means width of the single column (split
# at end of each column), not a width made up of multiple columns.
single_column_length = [cell_width, dp[colspan][index][colspan]].max
dp[colspan][index][colspan] = single_column_length
index += colspan
end
end
# run DP.
(1..n_cols).each do |colspan|
dp[colspan] ||= []
(0..n_cols-colspan).each do |index|
dp[colspan][index] ||= [1]
(1...colspan).each do |offset|
# processed level became reverse map from width => [offset, ...].
left_colspan = offset
left_index = index
left_width = dp[left_colspan][left_index].keys.first
right_colspan = colspan - left_colspan
right_index = index + offset
right_width = dp[right_colspan][right_index].keys.first
dp[colspan][index][offset] = left_width + right_width + space_width
end
# reverse map it for resolution (max width and short offset first).
rmap = {}
dp[colspan][index].each_with_index do |width, offset|
rmap[width] ||= []
rmap[width] << offset
end
# sort reversely and store it back.
dp[colspan][index] = Hash[rmap.sort.reverse]
end
end
resolve = lambda do |colspan, full_width, index = 0|
# stop if reaches the bottom level.
return @column_widths[index] = full_width if colspan == 1
# choose best split offset for partition, or second best result
# if first one is not dividable.
candidate_offsets = dp[colspan][index].collect(&:last).flatten
offset = candidate_offsets[0]
offset = candidate_offsets[1] if offset == colspan
# prepare for next round.
left_colspan = offset
left_index = index
left_width = dp[left_colspan][left_index].keys.first
right_colspan = colspan - left_colspan
right_index = index + offset
right_width = dp[right_colspan][right_index].keys.first
# calculate reference column width, give remaining spaces to left.
total_non_space_width = full_width - (colspan - 1) * space_width
ref_column_width = total_non_space_width / colspan
remainder = total_non_space_width % colspan
rem_left_width = [remainder, left_colspan].min
rem_right_width = remainder - rem_left_width
ref_left_width = ref_column_width * left_colspan +
(left_colspan - 1) * space_width + rem_left_width
ref_right_width = ref_column_width * right_colspan +
(right_colspan - 1) * space_width + rem_right_width
# at most one width can be greater than the reference width.
if left_width <= ref_left_width and right_width <= ref_right_width
# use refernce width (evenly partition).
left_width = ref_left_width
right_width = ref_right_width
else
# the wider one takes its value, shorter one takes the rest.
if left_width > ref_left_width
right_width = full_width - left_width - space_width
else
left_width = full_width - right_width - space_width
end
end
# run next round.
resolve.call(left_colspan, left_width, left_index)
resolve.call(right_colspan, right_width, right_index)
end
full_width = dp[n_cols][0].keys.first
unless style.width.nil?
new_width = style.width - space_width - style.border_y_width
if new_width < full_width
raise "Table width exceeds wanted width " +
"of #{style.width} characters."
end
full_width = new_width
end
resolve.call(n_cols, full_width)
end
##
# Return headings combined with rows.
def headings_with_rows
@headings + rows
end
def yield_or_eval &block
return unless block
if block.arity > 0
yield self
else
self.instance_eval(&block)
end
end
def title_cell_options
{:value => @title, :alignment => :center, :colspan => number_of_columns}
end
def require_column_widths_recalc
@require_column_widths_recalc = true
end
def column_widths
recalc_column_widths if @require_column_widths_recalc
@column_widths
end
end
end
terminal-table-4.0.0/lib/terminal-table/version.rb 0000644 0000041 0000041 00000000076 14753020547 022135 0 ustar www-data www-data module Terminal
class Table
VERSION = '4.0.0'
end
end
terminal-table-4.0.0/lib/terminal-table/style.rb 0000644 0000041 0000041 00000022237 14753020547 021613 0 ustar www-data www-data # coding: utf-8
require 'forwardable'
module Terminal
class Table
class Border
attr_accessor :data, :top, :bottom, :left, :right
def initialize
@top, @bottom, @left, @right = true, true, true, true
end
def []=(key, val)
@data[key] = val
end
def [](key)
@data[key]
end
def initialize_dup(other)
super
@data = other.data.dup
end
def remove_verticals
self.class.const_get("VERTICALS").each { |key| @data[key] = "" }
self.class.const_get("INTERSECTIONS").each { |key| @data[key] = "" }
end
def remove_horizontals
self.class.const_get("HORIZONTALS").each { |key| @data[key] = "" }
end
# If @left, return the edge else empty-string.
def maybeleft(key) ; @left ? @data[key] : '' ; end
# If @right, return the edge else empty-string.
def mayberight(key) ; @right ? @data[key] : '' ; end
end
class AsciiBorder < Border
HORIZONTALS = %i[x]
VERTICALS = %i[y]
INTERSECTIONS = %i[i]
def initialize
super
@data = { x: "-", y: "|", i: "+" }
end
# Get vertical border elements
# @return [Array] 3-element list of [left, center, right]
def vertical
[maybeleft(:y), @data[:y], mayberight(:y)] # left, center, right
end
# Get horizontal border elements
# @return [Array] a 6 element list of: [i-left, horizontal-bar, i-up/down, i-right, i-down, i-up]
def horizontal(_type)
x, i = @data[:x], @data[:i]
[maybeleft(:i), x, i, mayberight(:i), i, i]
end
end
class MarkdownBorder < AsciiBorder
def initialize
super
@top, @bottom = false, false
@data = { x: "-", y: "|", i: "|" }
end
end
class UnicodeBorder < Border
ALLOWED_SEPARATOR_BORDER_STYLES = %i[
top bot
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
]
HORIZONTALS = %i[x sx ax bx nx bx_dot3 bx_dot4 bx_dash x_dot3 x_dot4 x_dash]
VERTICALS = %i[y yw ye]
INTERSECTIONS = %i[nw n ne nd
aw ai ae ad au
bw bi be bd bu
w i e dn up
sw s se su]
def initialize
super
@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: '╍',
}
end
# Get vertical border elements
# @return [Array] 3-element list of [left, center, right]
def vertical
[maybeleft(:yw), @data[:y], mayberight(:ye)]
end
# Get horizontal border elements
# @return [Array] a 6 element list of: [i-left, horizontal-bar, i-up/down, i-right, i-down, i-up]
def horizontal(type)
raise ArgumentError, "Border type is #{type.inspect}, must be one of #{ALLOWED_SEPARATOR_BORDER_STYLES.inspect}" unless ALLOWED_SEPARATOR_BORDER_STYLES.include?(type)
lookup = case type
when :top
[:nw, :nx, :n, :ne, :n, nil]
when :bot
[:sw, :sx, :s, :se, nil, :s]
when :double
# typically used for the separator below the heading row or above a footer row)
[:aw, :ax, :ai, :ae, :ad, :au]
when :thick, :thick_dash, :thick_dot3, :thick_dot4,
:heavy, :heavy_dash, :heavy_dot3, :heavy_dot4,
:bold, :bold_dash, :bold_dot3, :bold_dot4
# alternate thick/bold border
xref = type.to_s.sub(/^(thick|heavy|bold)/,'bx').to_sym
[:bw, xref, :bi, :be, :bd, :bu]
when :dash, :dot3, :dot4
# alternate thin dividers
xref = "x_#{type}".to_sym
[:w, xref, :i, :e, :dn, :up]
else # :div (center, non-emphasized)
[:w, :x, :i, :e, :dn, :up]
end
rval = lookup.map { |key| @data.fetch(key) }
rval[0] = '' unless @left
rval[3] = '' unless @right
rval
end
end
# Unicode Border With rounded edges
class UnicodeRoundBorder < UnicodeBorder
def initialize
super
@data.merge!({nw: '╭', ne: '╮', sw: '╰', se: '╯'})
end
end
# Unicode Border with thick outer edges
class UnicodeThickEdgeBorder < UnicodeBorder
def initialize
super
@data = {
nil => nil,
nw: "┏", nx: "━", n: "┯", ne: "┓", nd: nil,
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: "┛", su: nil,
# alternative dots/dashes
x_dot4: '┈', x_dot3: '┄', x_dash: '╌',
bx_dot4: '┉', bx_dot3: '┅', bx_dash: '╍',
}
end
end
# A Style object holds all the formatting information for a Table object
#
# To create a table with a certain style, use either the constructor
# option :style, the Table#style object or the Table#style= method
#
# All these examples have the same effect:
#
# # by constructor
# @table = Table.new(:style => {:padding_left => 2, :width => 40})
#
# # by object
# @table.style.padding_left = 2
# @table.style.width = 40
#
# # by method
# @table.style = {:padding_left => 2, :width => 40}
#
# To set a default style for all tables created afterwards use Style.defaults=
#
# Terminal::Table::Style.defaults = {:width => 80}
#
class Style
extend Forwardable
def_delegators :@border, :vertical, :horizontal, :remove_verticals, :remove_horizontals
@@defaults = {
:border => AsciiBorder.new,
:padding_left => 1, :padding_right => 1,
:margin_left => '',
:width => nil, :alignment => nil,
:all_separators => false,
}
## settors/gettor for legacy ascii borders
def border_x=(val) ; @border[:x] = val ; end
def border_y=(val) ; @border[:y] = val ; end
def border_i=(val) ; @border[:i] = val ; end
def border_y ; @border[:y] ; end
def border_y_width ; Util::ansi_escape(@border[:y]).length ; end
# Accessor for instance of Border
attr_reader :border
def border=(val)
if val.is_a? Symbol
# convert symbol name like :foo_bar to get class FooBarBorder
klass_str = val.to_s.split('_').collect(&:capitalize).join + "Border"
begin
klass = Terminal::Table::const_get(klass_str)
@border = klass.new
rescue NameError
raise "Cannot lookup class Terminal::Table::#{klass_str} from symbol #{val.inspect}"
end
else
@border = val
end
end
def border_top=(val) ; @border.top = val ; end
def border_bottom=(val) ; @border.bottom = val ; end
def border_left=(val) ; @border.left = val ; end
def border_right=(val) ; @border.right = val ; end
def border_top ; @border.top ; end
def border_bottom ; @border.bottom ; end
def border_left ; @border.left ; end
def border_right ; @border.right ; end
attr_accessor :padding_left
attr_accessor :padding_right
attr_accessor :margin_left
attr_accessor :width
attr_accessor :alignment
attr_accessor :all_separators
def initialize options = {}
apply self.class.defaults.merge(options)
end
def apply options
options.each do |m, v|
__send__ "#{m}=", v
end
end
class << self
def defaults
klass_defaults = @@defaults.dup
# border is an object that needs to be duplicated on instantiation,
# otherwise everything will be referencing the same object-id.
klass_defaults[:border] = klass_defaults[:border].dup
klass_defaults
end
def defaults= options
@@defaults = defaults.merge(options)
end
end
def on_change attr
method_name = :"#{attr}="
old_method = method method_name
define_singleton_method(method_name) do |value|
old_method.call value
yield attr.to_sym, value
end
end
end
end
end
terminal-table-4.0.0/lib/terminal-table/table_helper.rb 0000644 0000041 0000041 00000000314 14753020547 023071 0 ustar www-data www-data module Terminal
class Table
module TableHelper
def table headings = [], *rows, &block
Terminal::Table.new :headings => headings.to_a, :rows => rows, &block
end
end
end
end
terminal-table-4.0.0/lib/terminal-table.rb 0000644 0000041 0000041 00000002350 14753020547 020445 0 ustar www-data www-data #--
# Copyright (c) 2008-2009 TJ Holowaychuk
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
%w(cell row separator style table table_helper util version).each do |file|
require_relative "./terminal-table/#{file}"
end
terminal-table-4.0.0/LICENSE.txt 0000644 0000041 0000041 00000002123 14753020547 016273 0 ustar www-data www-data The MIT License (MIT)
Copyright (c) 2008-2017 TJ Holowaychuk
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
terminal-table-4.0.0/Manifest 0000644 0000041 0000041 00000001101 14753020547 016134 0 ustar www-data www-data Gemfile
History.rdoc
README.rdoc
Rakefile
Todo.rdoc
examples/examples.rb
lib/terminal-table.rb
lib/terminal-table/cell.rb
lib/terminal-table/import.rb
lib/terminal-table/row.rb
lib/terminal-table/separator.rb
lib/terminal-table/style.rb
lib/terminal-table/table.rb
lib/terminal-table/table_helper.rb
lib/terminal-table/version.rb
spec/cell_spec.rb
spec/row_spec.rb
spec/spec_helper.rb
spec/table_helper_spec.rb
spec/table_spec.rb
tasks/docs.rake
tasks/gemspec.rake
tasks/spec.rake
terminal-table.gemspec
terminal-table.sublime-project
terminal-table.sublime-workspace
Manifest
terminal-table-4.0.0/Rakefile 0000644 0000041 0000041 00000000435 14753020547 016121 0 ustar www-data www-data require 'bundler'
Bundler.setup
Bundler::GemHelper.install_tasks
require 'rake'
require 'rspec/core/rake_task'
desc "Run all examples"
RSpec::Core::RakeTask.new(:spec) do |t|
t.ruby_opts = %w[-w]
t.rspec_opts = %w[--color]
end
desc "Default: Run specs"
task :default => [:spec]
terminal-table-4.0.0/Gemfile 0000644 0000041 0000041 00000000207 14753020547 015744 0 ustar www-data www-data source 'https://rubygems.org'
# Specify your gem's dependencies in test-gem.gemspec
gemspec
gem 'tins', '~> 1.0.0' # Ruby 1.9 compat
terminal-table-4.0.0/History.rdoc 0000644 0000041 0000041 00000007733 14753020547 016776 0 ustar www-data www-data 4.0.0 / 2025-01-28
==================
- Non-unicode characters are no longer supported. They will be replaced.
- Headings may be set to nil.
- unicode-display-width version 3 supported.
3.0.2 / 2021-09-19
==================
- fix align_column for nil values and colspan
3.0.1 / 2021-05-10
==================
- Support for unicode-display_width 2.0
- Fix issue where last row of an empty table changed format
3.0.0 / 2020-01-27
==================
- Support for (optional) Unicode border styles on tables. In order to support decent looking Unicode borders, different types of intersections get different types of intersection characters. This has the side effect of subtle formatting differences even for the ASCII table border case due to removal of certain intersections near colspans.
For example, previously the output of a table may be:
+------+-----+
| Title |
+------+-----+
| Char | Num |
+------+-----+
| a | 1 |
| b | 2 |
| c | 3 |
+------+-----+
And now the `+` character above the word Title is removed, as it is no longer considered an intersection:
+------------+
| Title |
+------+-----+
| Char | Num |
+------+-----+
| a | 1 |
| b | 2 |
+------+-----+
- The default border remains an ASCII border for backwards compatibility, however multiple border classes are included / documented, and user defined border types can be applied as needed.
In support of this update, the following issues were addressed:
- colspan creates conflict with colorize (#95)
- Use nice UTF box-drawing characters by default (#99)
- Note that `AsciiBorder` is stll the default
- Border-left and border-right style (#100)
- Helper function to style as Markdown (#111)
- Achieved using `MarkdownBorder`
2.0.0 / 2020-10-28
==================
- Drops official support for Ruby 1.9.x with and of life on 2015-02-23
- Drops official support for Ruby 2.0.x with and of life on 2016-02-24
- Drops official support for Ruby 2.1.x with and of life on 2017-03-31
- Drops official support for Ruby 2.2.x with and of life on 2018-03-31
- Drops official support for Ruby 2.3.x with and of life on 2019-03-31
1.8.0 / 2017-05-16
==================
* Top and bottom borders can be disabled (@kubakrzempek, #83)
* `unicode-display-width` dependency relaxes (@mvz, #88)
* Readme and docs fixes (@loualrid, #82 and @leoarnold, #86)
* Fixed some test-related warnings (@juanitofatas, #81 and @mvz, #89)
1.7.3 / 2016-09-21
==================
* Fixed compatibility issues for Ruby 1.9, 2.0, 2.1. (@vivekbisen, #80)
1.7.2 / 2016-09-09
==================
* Fix packing table to a minimal width (@vizv, #76)
1.7.1 / 2016-08-29
==================
* Update `unicode-display_width` to fix behavior with signal traps [#78, @jrmhaig]
1.7.0 / 2016-08-29
==================
All props to @vizv for this release!
* Fixed some spec failures
* Added support for full-width characters (East Asian alphabets, etc)
1.6.0 / 2016-06-06
==================
* Added table styles - margin_left, all_separators.
1.4.3 / 2011-10-13
==================
* Optimize for faster table output.
1.4.2 / 2010-01-14
==================
* Fixed some bugs with colspan
=== 1.4.1 / 2009-12-18
* Fix column alignment with separators.
=== 1.4.0 / 2009-12-18
* Can now add :seperator arbitrarily in a table [thanks splattael]
* Fix common typo: seperator -> separator [thanks splattael]
=== 1.3.0 / 2009-10-16
* Major refactoring (functionality remains the same)
=== 1.2.0 / 2009-08-06
* Added colspan support to table
=== 1.1.0 / 2009-08-06
* Added colspan support to table
=== 1.1.0 / 2009-07-13
* Added Table#==
=== 1.0.5 / 2009-03-14
* Allowing nil to be passed to table for headings
* Revised doc to show that rows can be splatted now
* Misc refactoring
=== 1.0.3 / 2009-01-15
* Moved yield or eval to Terminal::Table initialize where it belongs
=== 1.0.0 / 2009-01-13
* Initial release
terminal-table-4.0.0/Todo.rdoc 0000644 0000041 0000041 00000000306 14753020547 016227 0 ustar www-data www-data
== Major:
* Nothing
== Minor:
* Programmatically add separator rows
* Add multi-column sorting
* Change; pre-create Cell and Heading objects to clean up Table a bit
== Brainstorming:
* Nothing terminal-table-4.0.0/README.md 0000644 0000041 0000041 00000026574 14753020547 015747 0 ustar www-data www-data [](https://github.com/tj/terminal-table/actions)
[](https://badge.fury.io/rb/terminal-table)
# 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:
```ruby
require 'terminal-table'
```
To generate a table, provide an array of arrays (which are interpreted as
rows):
```ruby
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:
```ruby
table = Terminal::Table.new do |t|
t.rows = rows
end
table = Terminal::Table.new do
self.rows = rows
end
```
Adding rows one by one:
```ruby
table = Terminal::Table.new do |t|
t << ['One', 1]
t.add_row ['Two', 2]
end
```
To add separators between rows:
```ruby
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:
```ruby
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:
```ruby
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:
```ruby
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:
```ruby
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:
```ruby
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:
```ruby
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:
```ruby
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:
```ruby
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.
```ruby
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.
```ruby
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:
```ruby
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:
```ruby
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.
```ruby
@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_type`s 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.
```ruby
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.
```ruby
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.
```ruby
#!/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
Unicode table support by Ben Bowers https://github.com/nanobowers
terminal-table-4.0.0/examples/ 0000755 0000041 0000041 00000000000 14753020547 016270 5 ustar www-data www-data terminal-table-4.0.0/examples/data.csv 0000644 0000041 0000041 00000000176 14753020547 017722 0 ustar www-data www-data First Name,Last Name,Email
TJ,Holowaychuk,tj@vision-media.ca
Bob,Someone,bob@vision-media.ca
Joe,Whatever,joe@vision-media.ca
terminal-table-4.0.0/examples/issue111.rb 0000755 0000041 0000041 00000000323 14753020547 020171 0 ustar www-data www-data #!/usr/bin/env ruby
require_relative "../lib/terminal-table"
puts Terminal::Table.new(headings: ['heading A', 'heading B'], rows: [['a', 'b'], ['a', 'b']], style: {border: Terminal::Table::MarkdownBorder.new})
terminal-table-4.0.0/examples/examples.rb 0000755 0000041 0000041 00000004264 14753020547 020444 0 ustar www-data www-data $:.unshift File.dirname(__FILE__) + '/../lib'
require 'terminal-table/import'
puts
puts table(['a', 'b'], [1, 2], [3, 4])
puts
puts table(['name', 'content'], ['ftp.example.com', '1.1.1.1'], ['www.example.com', '|lalalala|lalala|'])
puts
t = table ['a', 'b']
t.style = {:padding_left => 2, :width => 80}
t << [1, 2]
t << [3, 4]
t << :separator
t << [4, 6]
puts t
puts
user_table = table do |v|
v.title = "Contact Information"
v.headings = 'First Name', 'Last Name', 'Email'
v << %w( TJ Holowaychuk tj@vision-media.ca )
v << %w( Bob Someone bob@vision-media.ca )
v << %w( Joe Whatever bob@vision-media.ca )
end
puts user_table
puts
user_table = table do |v|
v.style.width = 80
v.headings = 'First Name', 'Last Name', 'Email'
v << %w( TJ Holowaychuk tj@vision-media.ca )
v << %w( Bob Someone bob@vision-media.ca )
v << %w( Joe Whatever bob@vision-media.ca )
end
puts user_table
puts
user_table = table do
self.headings = 'First Name', 'Last Name', 'Email'
add_row ['TJ', 'Holowaychuk', 'tj@vision-media.ca']
add_row ['Bob', 'Someone', 'bob@vision-media.ca']
add_row ['Joe', 'Whatever', 'joe@vision-media.ca']
add_separator
add_row ['Total', { :value => '3', :colspan => 2, :alignment => :right }]
align_column 1, :center
end
puts user_table
puts
user_table = table do
self.headings = ['First Name', 'Last Name', {:value => 'Phones', :colspan => 2, :alignment => :center}]
add_row ['Bob', 'Someone', '123', '456']
add_row :separator
add_row ['TJ', 'Holowaychuk', {:value => "No phones\navaiable", :colspan => 2, :alignment => :center}]
add_row :separator
add_row ['Joe', 'Whatever', '4324', '343242']
end
puts user_table
rows = []
rows << ['Lines', 100]
rows << ['Comments', 20]
rows << ['Ruby', 70]
rows << ['JavaScript', 30]
puts table([nil, 'Lines'], *rows)
rows = []
rows << ['Lines', 100]
rows << ['Comments', 20]
rows << ['Ruby', 70]
rows << ['JavaScript', 30]
puts table(nil, *rows)
rows = []
rows << ['Lines', 100]
rows << ['Comments', 20]
rows << ['Ruby', 70]
rows << ['JavaScript', 30]
table = table([{ :value => 'Stats', :colspan => 2, :alignment => :center }], *rows)
table.align_column 1, :right
puts table
terminal-table-4.0.0/examples/show_csv_table.rb 0000755 0000041 0000041 00000001461 14753020547 021624 0 ustar www-data www-data #!/usr/bin/env ruby
require "csv"
$LOAD_PATH << "#{__dir__}/../lib"
require "terminal-table"
#
# Usage:
# ./show_csv_table.rb data.csv
# cat data.csv | ./show_csv_table.rb
# cat data.csv | ./show_csv_table.rb -
#
#
# Reads a CSV from $stdin if no argument given, or argument is '-'
# otherwise interprets first cmdline argument as the CSV filename
#
use_stdin = ARGV[0].nil? || (ARGV[0] == '-')
io_object = use_stdin ? $stdin : File.open(ARGV[0], 'r')
csv = CSV.new(io_object)
#
# Convert to an array for use w/ terminal-table
# The assumption is that this is a pretty small spreadsheet.
#
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
terminal-table-4.0.0/examples/issue118.rb 0000755 0000041 0000041 00000001241 14753020547 020200 0 ustar www-data www-data #!/usr/bin/env ruby
require_relative '../lib/terminal-table'
puts Terminal::Table.new(headings: ['a', 'b', 'c', 'd'], style: { border: :unicode })
puts
tbl = Terminal::Table.new do |t|
t.style = { border: :unicode }
t.add_separator
t.add_separator
t.add_row ['x','y','z']
t.add_separator
t.add_separator
end
puts tbl
puts
puts Terminal::Table.new(headings: [['a', 'b', 'c', 'd'], ['cat','dog','frog','mouse']], style: { border: :unicode })
puts
puts Terminal::Table.new(headings: ['a', 'b', 'c', 'd'])
puts
tbl = Terminal::Table.new do |t|
t.add_separator
t.add_separator
t.add_row ['x','y','z']
t.add_separator
t.add_separator
end
puts tbl
terminal-table-4.0.0/examples/examples_unicode.rb 0000755 0000041 0000041 00000004621 14753020547 022147 0 ustar www-data www-data #!/usr/bin/env ruby
$:.unshift File.dirname(__FILE__) + '/../lib'
require 'terminal-table/import'
Terminal::Table::Style.defaults = { :border => :unicode_round }
# Terminal::Table::UnicodeThickEdgeBorder.new()
puts
puts table(['a', 'b'], [1, 2], [3, 4])
puts
puts table(['name', 'content'], ['ftp.example.com', '1.1.1.1'], ['www.example.com', '|lalalala|lalala|'])
puts
t = table ['a', 'b']
t.style = {:padding_left => 2, :width => 80}
t << [1, 2]
t << [3, 4]
t << :separator
t << [4, 6]
puts t
puts
user_table = table do |v|
v.title = "Contact Information"
v.headings = 'First Name', 'Last Name', 'Email'
v << %w( TJ Holowaychuk tj@vision-media.ca )
v << %w( Bob Someone bob@vision-media.ca )
v << %w( Joe Whatever bob@vision-media.ca )
end
puts user_table
puts
user_table = table do |v|
v.style.width = 80
v.headings = 'First Name', 'Last Name', 'Email'
v << %w( TJ Holowaychuk tj@vision-media.ca )
v << %w( Bob Someone bob@vision-media.ca )
v << %w( Joe Whatever bob@vision-media.ca )
end
puts user_table
puts
user_table = table do
self.headings = 'First Name', 'Last Name', 'Email'
add_row ['TJ', 'Holowaychuk', 'tj@vision-media.ca']
add_row ['Bob', 'Someone', 'bob@vision-media.ca']
add_row ['Joe', 'Whatever', 'joe@vision-media.ca']
add_separator
add_row ['Total', { :value => '3', :colspan => 2, :alignment => :right }]
align_column 1, :center
end
puts user_table
puts
user_table = table do
self.headings = ['First Name', 'Last Name', {:value => 'Phones', :colspan => 2, :alignment => :center}]
#add_row ['Bob', 'Someone', '123', '456']
add_row [{:value => "Bob Someone", :colspan => 3, :alignment => :center}, '123456']
add_row :separator
add_row ['TJ', 'Holowaychuk', {:value => "No phones\navaiable", :colspan => 2, :alignment => :center}]
add_row :separator
add_row ['Joe', 'Whatever', '4324', '343242']
end
puts user_table
rows = []
rows << ['Lines', 100]
rows << ['Comments', 20]
rows << ['Ruby', 70]
rows << ['JavaScript', 30]
puts table([nil, 'Lines'], *rows)
rows = []
rows << ['Lines', 100]
rows << ['Comments', 20]
rows << ['Ruby', 70]
rows << ['JavaScript', 30]
puts table(nil, *rows)
rows = []
rows << ['Lines', 100]
rows << ['Comments', 20]
rows << ['Ruby', 70]
rows << ['JavaScript', 30]
table = table([{ :value => 'Stats', :colspan => 2, :alignment => :center }], *rows)
table.align_column 1, :right
puts table
terminal-table-4.0.0/examples/issue95.rb 0000755 0000041 0000041 00000002472 14753020547 020133 0 ustar www-data www-data #!/usr/bin/env ruby
require 'colorize'
require_relative '../lib/terminal-table.rb'
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 table"
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
table = Terminal::Table.new headings: ["Month","Monthly IT",
{value: "IT Difference OPM", colspan: 2}, "Monthly OOT",
{value: "OOT Difference OPM", colspan: 2}], rows: split_column_sample_data
table.style = { padding_left: 2, padding_right: 2, border_x: "-".blue, border_y: "|".cyan, border_i: "+" }
puts table
terminal-table-4.0.0/examples/issue100.rb 0000755 0000041 0000041 00000001306 14753020547 020171 0 ustar www-data www-data #!/usr/bin/env ruby
# Methods to suppress left/right borders using border_left & border_right
require_relative "../lib/terminal-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_top => false, :border_bottom => false }
end
puts table
puts
# no right
table.style = {:border_right => false }
puts table
puts
# no right
table.style = {:border_left => true }
puts table
puts
table.style.border = Terminal::Table::UnicodeBorder.new
puts table
table.style = {:border_right => false, :border_left => true }
puts table
table.style = {:border_right => true, :border_left => false }
puts table
terminal-table-4.0.0/examples/strong_separator.rb 0000755 0000041 0000041 00000000756 14753020547 022224 0 ustar www-data www-data #!/usr/bin/env ruby
require_relative "../lib/terminal-table"
#
# An example of how to manually add separators with non-default
# border_type to enable a footer row.
#
table = Terminal::Table.new do |t|
# set the style
t.style = { border: :unicode_thick_edge }
# header row
t.headings = ['fruit', 'count']
# some row data
t.add_row ['apples', 7]
t.add_row ['bananas', 19]
t.add_separator border_type: :strong
# footer row
t.add_row ['total', 26]
end
puts table.render