Module: CLI::UI::Table

Extended by:
T::Sig
Defined in:
lib/cli/ui/table.rb

Class Method Summary collapse

Methods included from T::Sig

sig

Class Method Details

.capture_table(table, col_spacing: 1) ⇒ Object



79
80
81
82
83
# File 'lib/cli/ui/table.rb', line 79

def capture_table(table, col_spacing: 1)
  strio = StringIO.new
  puts_table(table, col_spacing: col_spacing, to: strio)
  strio.string.lines.map(&:chomp)
end

.puts_table(table, col_spacing: 1, to: $stdout) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/cli/ui/table.rb', line 39

def puts_table(table, col_spacing: 1, to: $stdout)
  col_sizes = table.transpose.map do |col|
    col.map { |cell| CLI::UI::ANSI.printing_width(CLI::UI.resolve_text(cell)) }.max
  end

  table.each do |row|
    padded_row = row.each_with_index.map do |cell, i|
      col_size = T.must(col_sizes[i]) # guaranteed to be non-nil
      cell_size = CLI::UI::ANSI.printing_width(CLI::UI.resolve_text(cell))
      padded_cell = cell + ' ' * (col_size - cell_size)
      padded_cell
    end
    CLI::UI.puts(padded_row.join(' ' * col_spacing), to: to)
  end
end