module TTY::Table::Columns
A module for calculating table data column widths
Used by {Table} to manage column sizing.
@api private
Public Class Methods
assert_widths(column_widths, table_widths)
click to toggle source
Assert data integrity for column widths
@param [Array] column_widths
@param [Integer] table_widths
@raise [TTY::InvalidArgument]
@api public
# File lib/tty/table/columns.rb, line 85 def assert_widths(column_widths, table_widths) if column_widths.empty? fail InvalidArgument, 'Value for :column_widths must be ' \ 'a non-empty array' end if column_widths.size != table_widths fail InvalidArgument, 'Value for :column_widths must match ' \ 'table column count' end end
extract_widths(data)
click to toggle source
Calcualte maximum column widths
@return [Array] column widths
@api private
# File lib/tty/table/columns.rb, line 27 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)
click to toggle source
Find a maximum column width. The calculation takes into account wether the content is escaped or not.
@param [Integer] index
the column index
@return [Integer]
@api private
# File lib/tty/table/columns.rb, line 45 def find_maximum(data, index) data.map do |row| (field = row.call(index)) ? field.length : 0 end.max end
total_width(data)
click to toggle source
Calculate total table width
@return [Integer]
@api public
# File lib/tty/table/columns.rb, line 17 def total_width(data) extract_widths(data).reduce(:+) end
widths_from(table, column_widths = nil)
click to toggle source
Converts column widths to array format or infers default widths
@param [TTY::Table] table
@param [Array, Numeric, NilClass] column_widths
@return [Array]
@api public
# File lib/tty/table/columns.rb, line 61 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 fail TypeError, 'Invalid type for column widths' end end