Class: TTY::Table::ColumnSet

Inherits:
Object
  • Object
show all
Includes:
Equatable
Defined in:
lib/tty/table/column_set.rb

Overview

A class that represents table columns properties.

Instance Attribute Summary collapse

Attributes included from Equatable

#comparison_attrs

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Equatable

#attr_reader, included, #inherited

Constructor Details

#initialize(table) ⇒ ColumnSet

Initialize a ColumnSet



15
16
17
# File 'lib/tty/table/column_set.rb', line 15

def initialize(table)
  @table = table
end

Instance Attribute Details

#tableObject (readonly)

Returns the value of attribute table.



10
11
12
# File 'lib/tty/table/column_set.rb', line 10

def table
  @table
end

Class Method Details

.assert_widths(column_widths, table_widths) ⇒ Object

Assert data integrity for column widths

Parameters:

  • column_widths (Array)
  • table_widths (Integer)

Raises:



49
50
51
52
53
54
55
56
# File 'lib/tty/table/column_set.rb', line 49

def self.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

.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])


67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/tty/table/column_set.rb', line 67

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

Instance Method Details

#extract_widthsArray

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



33
34
35
36
37
38
# File 'lib/tty/table/column_set.rb', line 33

def extract_widths
  data     = table.data
  colcount = data.max { |row_a, row_b| row_a.size <=> row_b.size }.size

  self.class.find_maximas(colcount, data)
end

#total_widthInteger

Calculate total table width

Returns:

  • (Integer)


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

def total_width
  extract_widths.reduce(:+)
end