Class: BooticCli::Formatters::Table

Inherits:
Object
  • Object
show all
Defined in:
lib/bootic_cli/formatters.rb

Constant Summary collapse

CELL_PADDING =
5.freeze

Instance Method Summary collapse

Instance Method Details

#format(array_of_arrays, headings = true) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/bootic_cli/formatters.rb', line 10

def format(array_of_arrays, headings = true)
  array_of_arrays = array_of_arrays.dup

  # [122, 23, 45, 66]
  cell_sizes = array_of_arrays.each.with_object([]) do |row, memo|
    row.each.with_index do |cell, idx|
      if !memo[idx] || memo[idx] < cell.size
        memo[idx] = cell.size
      end
    end
  end

  data = array_of_arrays.map do |row|
    row.map.with_index{|e, idx|
      e.to_s.ljust(cell_sizes[idx] + CELL_PADDING)
    }.join(' | ')
  end

  if headings
    sep = cell_sizes.map{|i| '-' * (i + CELL_PADDING)}.join('-|-')
    data.insert(1, sep)
  end

  data.join("\r\n")

end