Class: TTY::Table

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Comparable, Enumerable, Conversion, Equatable, Validatable
Defined in:
lib/tty/table.rb,
lib/tty/table/row.rb,
lib/tty/table/error.rb,
lib/tty/table/field.rb,
lib/tty/table/border.rb,
lib/tty/table/header.rb,
lib/tty/table/renderer.rb,
lib/tty/table/border_dsl.rb,
lib/tty/table/column_set.rb,
lib/tty/table/operations.rb,
lib/tty/table/border/null.rb,
lib/tty/table/orientation.rb,
lib/tty/table/validatable.rb,
lib/tty/table/border/ascii.rb,
lib/tty/table/border/unicode.rb,
lib/tty/table/border_options.rb,
lib/tty/table/renderer/ascii.rb,
lib/tty/table/renderer/basic.rb,
lib/tty/table/renderer/color.rb,
lib/tty/table/transformation.rb,
lib/tty/table/border/row_line.rb,
lib/tty/table/operation/escape.rb,
lib/tty/table/operation/filter.rb,
lib/tty/table/renderer/unicode.rb,
lib/tty/table/operation/wrapped.rb,
lib/tty/table/operation/alignment.rb,
lib/tty/table/operation/truncation.rb,
lib/tty/table/orientation/vertical.rb,
lib/tty/table/orientation/horizontal.rb,
lib/tty/table/operation/alignment_set.rb

Overview

A core class intended for storing data in a structured, tabular form. Once the data is stored in a TTY::Table various operations can be performed before the information is dumped into a stdout.

Defined Under Namespace

Modules: Operation, Validatable Classes: Border, BorderDSL, BorderOptions, ColumnSet, DimensionMismatchError, Field, Header, Operations, Orientation, Renderer, Row, Transformation, TupleMissing

Constant Summary

Constants included from Validatable

Validatable::MIN_CELL_WIDTH

Instance Attribute Summary collapse

Attributes included from Equatable

#comparison_attrs

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Validatable

#assert_matching_widths, #assert_row_sizes, #assert_string_values, #validate_options!, #validate_rendering_options!

Methods included from Equatable

#attr_reader, included, #inherited

Methods included from Conversion

#convert_to_array

Constructor Details

#initialize(options = {}, &block) ⇒ TTY::Table

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Initialize a Table

Parameters:

  • options (Hash) (defaults to: {})

    the options to create the table with

Options Hash (options):

  • :header (String)

    column names to be displayed

  • :rows (String)

    Array of Arrays expressing the rows

  • :orientation (Symbol)

    used to transform table orientation



99
100
101
102
103
104
105
106
107
108
109
# File 'lib/tty/table.rb', line 99

def initialize(options={}, &block)
  validate_options! options
  @header        = (value = options[:header]) ? Header.new(value) : nil
  @rows          = coerce(options.fetch(:rows) { Row.new([]) })
  @orientation   = Orientation.coerce(options.fetch(:orientation) { :horizontal })
  @rotated       = false
  # TODO: assert that row_size is the same as column widths & aligns
  assert_row_sizes @rows
  @orientation.transform(self)
  yield_or_eval(&block) if block_given?
end

Instance Attribute Details

#headerEnumerable (readonly)

The table header

Returns:

  • (Enumerable)


25
26
27
# File 'lib/tty/table.rb', line 25

def header
  @header
end

#orientationObject

The table orientation out of :horizontal and :vertical



40
41
42
# File 'lib/tty/table.rb', line 40

def orientation
  @orientation
end

#rowsEnumerable (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

The table rows

Returns:

  • (Enumerable)


32
33
34
# File 'lib/tty/table.rb', line 32

def rows
  @rows
end

Class Method Details

.[](*rows) ⇒ Object

Create a new Table where each argument is a row

Examples:

table = TTY::Table.new[['a1', 'a2'], ['b1', 'b2']]


52
53
54
# File 'lib/tty/table.rb', line 52

def self.[](*rows)
  self.new(rows: rows)
end

.new(*args, &block) ⇒ Object

Instantiate a new Table

Examples:

of no header

rows  = [ ['a1', 'a2'], ['b1', 'b2'] ]
table = Table.new rows

of direct parameters

rows  = [ ['a1', 'a2'], ['b1', 'b2'] ]
table = Table.new ['Header 1', 'Header 2'], rows

of parameters passed as options

rows  = [ ['a1', 'a2'], ['b1', 'b2'] ]
table = Table.new :header => ['Header 1', 'Header 2'], :rows => rows

of parameters passed as hash

Table.new [ {'Header1' => ['a1','a2'], 'Header2' => ['b1', 'b2'] }] }

Parameters:

  • *args (Array[Symbol], Hash)


76
77
78
79
80
81
82
83
# File 'lib/tty/table.rb', line 76

def self.new(*args, &block)
  options = Utils.extract_options!(args)
  if args.size.nonzero?
    super(Transformation.extract_tuples(args).merge(options), &block)
  else
    super(options, &block)
  end
end

Instance Method Details

#<<(row) ⇒ self

Add row to table

Parameters:

  • row (Array)

Returns:

  • (self)


257
258
259
260
261
262
# File 'lib/tty/table.rb', line 257

def <<(row)
  rows_copy = rows.dup
  assert_row_sizes rows_copy << row
  rows << to_row(row)
  self
end

#[](i, j = false) ⇒ Object Also known as: at, element, component

Lookup element of the table given a row(i) and column(j)



173
174
175
176
177
178
179
180
# File 'lib/tty/table.rb', line 173

def [](i, j=false)
  return row(i) unless j
  if i >= 0 && j >= 0
    rows.fetch(i) { return nil }[j]
  else
    raise TTY::Table::TupleMissing.new(i,j)
  end
end

#[]=(i, j, val) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Set table value at row(i) and column(j)



188
189
190
# File 'lib/tty/table.rb', line 188

def []=(i, j, val)
  @rows[i][j] = val
end

#coerce(rows) ⇒ Array

Coerce an Enumerable into a Table This coercion mechanism is used by Table to handle Enumerable types and force them into array type.

Parameters:

  • object (Enumerable)

    the object to coerce

Returns:

  • (Array)


430
431
432
433
# File 'lib/tty/table.rb', line 430

def coerce(rows)
  rows = convert_to_array(rows)
  rows.map { |row| to_row(row, header) }
end

#column(index) { ... } ⇒ self

Return a column number at the index of the table as an Array. If the table has a header then column can be searched by header name. When a block is given, the elements of that Array are iterated over.

Examples:

header = [:h1, :h2]
rows  = [ ['a1', 'a2'], ['b1', 'b2'] ]
table = TTY::Table.new :rows => rows, :header => header
table.column(1)
table.column(1)   { |element| ... }
table.column(:h1)
table.column(:h1) { |element| ... }

Parameters:

  • index (Integer, String, Symbol)

Yields:

  • optional block to execute in the iteration operation

Returns:

  • (self)


239
240
241
242
243
244
245
246
247
248
# File 'lib/tty/table.rb', line 239

def column(index)
  index_unknown = index.is_a?(Integer) && (index >= column_size || index < 0)
  if block_given?
    return self if index_unknown
    rows.map { |row| yield row[index] }
  else
    return nil if index_unknown
    rows.map { |row| row[index] }.compact
  end
end

#column_sizeInteger

Return the number of columns

Examples:

table.column_size # => 5

Returns:

  • (Integer)


316
317
318
319
# File 'lib/tty/table.rb', line 316

def column_size
  return rows[0].size if rows.size > 0
  return 0
end

#dataArray

Provides access to all table data

Returns:

  • (Array)


116
117
118
# File 'lib/tty/table.rb', line 116

def data
  (header && !header.empty?) ? [header] + rows : rows
end

#each {|Array[Array]| ... } ⇒ self

Iterate over each tuple in the set

Examples:

table = TTY::Table.new(header, tuples)
table.each { |row| ... }

Yields:

  • (Array[Array])

Returns:

  • (self)


275
276
277
278
279
# File 'lib/tty/table.rb', line 275

def each
  return to_enum unless block_given?
  data.each { |row| yield row }
  self
end

#each_with_indexObject

Iterate over each element yielding in addition row and column index

Examples:

table = TTY::Table.new(header, tuples)
table.each_with_index { |el, row, col| puts "#{el} at #{row},#{col}" }

Returns:

  • self



290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/tty/table.rb', line 290

def each_with_index
  return to_enum unless block_given?
  start_index = 0
  if header && !header.empty?
    header.attributes.each_with_index do |el, col_index|
      yield el, 0, col_index
    end
    start_index = 1
  end

  rows.each_with_index do |row, row_index|
    row.fields.each_with_index do |el, col_index|
      yield el, row_index + start_index, col_index
    end
  end
  self
end

#empty?Boolean

Return true if this is an empty table, i.e. if the number of rows or the number of columns is 0

Returns:

  • (Boolean)


360
361
362
# File 'lib/tty/table.rb', line 360

def empty?
  column_size == 0 || row_size == 0
end

#render(*args) {|renderer| ... } ⇒ String

Render a given table. This method takes options which will be passed to the renderer prior to rendering, which allows the caller to set any table rendering variables.

Parameters:

  • renderer_type (Symbol)

    the renderer to be used

  • options (Hash)

Yields:

  • (renderer)

Yield Parameters:

Returns:

  • (String)


390
391
392
# File 'lib/tty/table.rb', line 390

def render(*args, &block)
  render_with(nil, *args, &block)
end

#render_with(border_class, renderer_type = (not_set=true), options = {}) {|renderer| ... } ⇒ String

Render a given table using custom border class.

Parameters:

Yields:

  • (renderer)

Yield Parameters:

Returns:

  • (String)


408
409
410
411
412
413
414
415
416
417
418
# File 'lib/tty/table.rb', line 408

def render_with(border_class, renderer_type=(not_set=true), options={}, &block)
  unless not_set
    if renderer_type.respond_to?(:to_hash)
      options = renderer_type
    else
      options[:renderer] = renderer_type
    end
  end

  Renderer.render_with(border_class, self, options, &block)
end

#rotateself

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Rotate the table between vertical and horizontal orientation

Returns:

  • (self)


143
144
145
146
# File 'lib/tty/table.rb', line 143

def rotate
  orientation.transform(self)
  self
end

#rotate_horizontalObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Rotate the table horizontally



160
161
162
163
164
165
166
167
168
# File 'lib/tty/table.rb', line 160

def rotate_horizontal
  transposed = rows.transpose
  if header && header.empty?
    @header = transposed[0]
    @rows   = transposed[1..-1].map { |row| to_row(row, @header) }
  elsif rotated?
    @rows = transposed.map { |row| to_row(row) }
  end
end

#rotate_verticalObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Rotate the table vertically



151
152
153
154
155
# File 'lib/tty/table.rb', line 151

def rotate_vertical
  @rows    = ([header].compact + rows).transpose.map { |row| to_row(row) }
  @header  = [] if header
  @rotated = true
end

#rotated?Boolean

Marks this table as rotated

Returns:

  • (Boolean)


134
135
136
# File 'lib/tty/table.rb', line 134

def rotated?
  @rotated
end

#row(index) { ... } ⇒ self

Return a row number at the index of the table as an Array. When a block is given, the elements of that Array are iterated over.

Examples:

rows  = [ ['a1', 'a2'], ['b1', 'b2'] ]
table = TTY::Table.new :rows => rows
table.row(1) { |element| ... }

Parameters:

  • index (Integer)

Yields:

  • optional block to execute in the iteration operation

Returns:

  • (self)


209
210
211
212
213
214
215
216
# File 'lib/tty/table.rb', line 209

def row(index, &block)
  if block_given?
    rows.fetch(index) { return self }.each(&block)
    self
  else
    rows.fetch(index) { return nil }
  end
end

#row_sizeInteger

Return the number of rows

Examples:

table.row_size # => 5

Returns:

  • (Integer)


329
330
331
# File 'lib/tty/table.rb', line 329

def row_size
  rows.size
end

#sizeArray

Return the number of rows and columns

Examples:

table.size # => [3,5]

Returns:

  • (Array)

    row x columns



341
342
343
# File 'lib/tty/table.rb', line 341

def size
  [row_size, column_size]
end

#to_header(row) ⇒ TTY::Table::Header

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Convert an Array row into Header

Returns:



14
15
16
# File 'lib/tty/table/header.rb', line 14

def to_header(row)
  Header.new(row)
end

#to_row(row, header = nil) ⇒ TTY::Table::Row

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Convert an Array row into Row

Returns:



13
14
15
# File 'lib/tty/table/row.rb', line 13

def to_row(row, header=nil)
  Row.new(row, header)
end

#to_sString

Return string representation of table using basic renderer.

Returns:

  • (String)


369
370
371
# File 'lib/tty/table.rb', line 369

def to_s
  render(:basic)
end

#widthInteger

Check table width

Returns:

  • (Integer)

    width



350
351
352
# File 'lib/tty/table.rb', line 350

def width
  ColumnSet.new(self).total_width
end