Class: Table

Inherits:
Object
  • Object
show all
Defined in:
lib/galaxy/table.rb

Instance Method Summary collapse

Constructor Details

#initialize(headers = nil, rows = nil) ⇒ Table

Returns a new instance of Table.



4
5
6
7
# File 'lib/galaxy/table.rb', line 4

def initialize(headers = nil, rows = nil)
  @headers = headers
  @rows = rows || []
end

Instance Method Details

#<<(row) ⇒ Object



9
10
11
# File 'lib/galaxy/table.rb', line 9

def <<(row)
  @rows << row
end

#calculate_widthsObject



13
14
15
16
17
18
19
# File 'lib/galaxy/table.rb', line 13

def calculate_widths
  (@rows + [@headers]).
          map { |cols| cols.map { |col| Colorize::strip_colors(col) }.map(&:size) }.
          transpose.
          slice(0..-2).  # don't pad last column
          map(&:max)
end

#render(tty = true) ⇒ Object



21
22
23
24
25
26
27
28
# File 'lib/galaxy/table.rb', line 21

def render(tty = true)
  widths = calculate_widths

  rows = @rows
  rows = [@headers] + rows if tty

  rows.map { |row| render_row(row, widths, tty) }.join("\n")
end

#render_row(row, col_widths, tty) ⇒ Object



30
31
32
33
34
35
36
37
38
39
# File 'lib/galaxy/table.rb', line 30

def render_row(row, col_widths, tty)
  if tty
    row.zip(col_widths).map do |value, width|
      width ||= Colorize.strip_colors(value).length
      value + ' ' * (width - Colorize.strip_colors(value).length)
    end.join('  ')
  else
    row.map { |value| Colorize.strip_colors(value) }.join("\t")
  end
end