class IO::Table

Table Component.

Constants

BORDER

the table border character.

Public Class Methods

new() click to toggle source
# File lib/term/table.rb, line 18
def initialize
  @data = []
  @size = []
  @column_width = []
end

Public Instance Methods

<<(row) click to toggle source

add row to the table

@param row [Array] the row to the table @return [self] table self

# File lib/term/table.rb, line 28
def <<(row)
  @data << row.map(&:to_s)
  @size << row.map { |cell| cell.to_s.display_width }
  self
end
to_s() click to toggle source

display table.

@return [String] the table

# File lib/term/table.rb, line 37
def to_s
  @column_width = calc_column_width
  res = get_border_row(BORDER[:top])
  res << @data.map { |row| get_content_row(row, BORDER[:sep]) }
         .join(get_border_row(BORDER[:mid]))
  res << get_border_row(BORDER[:bot])
end

Private Instance Methods

calc_column_width() click to toggle source

get column width.

# File lib/term/table.rb, line 48
def calc_column_width
  @size.transpose.map(&:max)
end
get_border_row(border) click to toggle source

get border row.

# File lib/term/table.rb, line 53
def get_border_row(border)
  left, mid, right = border
  line = @column_width.map { |size| BORDER[:line] * size }.join(mid)
  "#{left}#{line}#{right}#{$/}"
end
get_content_row(row, sep) click to toggle source

get content row.

# File lib/term/table.rb, line 60
def get_content_row(row, sep)
  res = ''
  row.each_with_index do |cell, column|
    size = @column_width[column] - cell.display_width
    res << "#{cell}#{' ' * size}#{sep}"
  end
  "#{sep}#{res}#{$/}"
end