Class: CoinSync::TablePrinter

Inherits:
Object
  • Object
show all
Defined in:
lib/coinsync/table_printer.rb

Instance Method Summary collapse

Instance Method Details



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/coinsync/table_printer.rb', line 3

def print_table(header, rows, alignment: nil, separator: '  ')
  rows.each do |row|
    if row.length != header.length
      raise "TablePrinter: All rows should have equal number of cells"
    end

    if !row.all? { |c| c.is_a?(String) }
      raise "TablePrinter: All cells should be strings"
    end
  end

  ids = (0...header.length)
  widths = ids.map { |i| (rows + [header]).map { |r| r[i].length }.max }

  puts ids.map { |i| header[i].center(widths[i]) }.join(separator)
  puts '-' * (widths.inject(&:+) + separator.length * (header.length - 1))

  rows.each do |row|
    cells = ids.map do |i|
      row[i].send(alignment && alignment[i] || :ljust, widths[i])
    end

    puts cells.join(separator)
  end
end