Module: TTY::Table::Columns Private

Defined in:
lib/tty/table/columns.rb

Overview

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

A module for calculating table data column widths

Used by TTY::Table to manage column sizing.

Class Method Summary collapse

Class Method Details

.assert_widths(column_widths, table_widths) ⇒ Object

Assert data integrity for column widths

Parameters:

  • column_widths (Array)
  • table_widths (Integer)

Raises:

  • (TTY::InvalidArgument)


86
87
88
89
90
91
92
93
94
95
# File 'lib/tty/table/columns.rb', line 86

def assert_widths(column_widths, table_widths)
  if column_widths.empty?
    raise InvalidArgument, "Value for :column_widths must be " \
                           "a non-empty array"
  end
  if column_widths.size != table_widths
    raise InvalidArgument, "Value for :column_widths must match " \
                           "table column count"
  end
end

.extract_widths(data) ⇒ Array

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.

Calcualte maximum column widths

Returns:

  • (Array)

    column widths



28
29
30
31
32
33
34
# File 'lib/tty/table/columns.rb', line 28

def extract_widths(data)
  colcount = data.max { |row_a, row_b| row_a.size <=> row_b.size }.size
  (0...colcount).reduce([]) do |maximas, col_index|
    maximas << find_maximum(data, col_index)
    maximas
  end
end

.find_maximum(data, index) ⇒ Integer

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.

Find a maximum column width. The calculation takes into account wether the content is escaped or not.

Parameters:

  • index (Integer)

    the column index

Returns:

  • (Integer)


46
47
48
49
50
# File 'lib/tty/table/columns.rb', line 46

def find_maximum(data, index)
  data.map do |row|
    (field = row.call(index)) ? field.length : 0
  end.max
end

.total_width(data) ⇒ Integer

Calculate total table width

Returns:

  • (Integer)


18
19
20
# File 'lib/tty/table/columns.rb', line 18

def total_width(data)
  extract_widths(data).reduce(:+)
end

.widths_from(table, column_widths = nil) ⇒ Array[Integer]

Converts column widths to array format or infers default widths

Parameters:

  • table (TTY::Table)
  • column_widths (Array, Numeric, NilClass) (defaults to: nil)

Returns:

  • (Array[Integer])


62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/tty/table/columns.rb', line 62

def widths_from(table, column_widths = nil)
  case column_widths
  when Array
    assert_widths(column_widths, table.columns_size)
    Array(column_widths).map(&:to_i)
  when Numeric
    Array.new(table.columns_size, column_widths)
  when NilClass
    extract_widths(table.data)
  else
    raise TypeError, "Invalid type for column widths"
  end
end