Class: Tableizer::TextTable

Inherits:
Object
  • Object
show all
Defined in:
lib/tableizer/text_table.rb

Instance Method Summary collapse

Instance Method Details

#col_widths(headers, rows) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/tableizer/text_table.rb', line 23

def col_widths(headers, rows)
  rows = [headers] + rows
  widths = Array.new(headers.length, 0)
  rows.each do |row|
    row.each_with_index do |col, index|
      width = col.to_s.length || 0
      widths[index] = width if width > widths.fetch(index) 
    end
  end
  widths
end

#row_str(row, col_widths) ⇒ Object



13
14
15
16
17
# File 'lib/tableizer/text_table.rb', line 13

def row_str(row, col_widths)
  row.each_with_index.map do |val, index|
    value_to_str(val, col_widths.fetch(index))
  end.join('|')
end

#to_s(cols_info, rows) ⇒ Object



3
4
5
6
7
8
9
10
11
# File 'lib/tableizer/text_table.rb', line 3

def to_s(cols_info, rows)
  headers = cols_info.map(&:header)
  widths = col_widths(headers, rows)
  text = ""
  text << row_str(headers, widths) + "\n"
  text << rows.map do |cols| 
    row_str(cols, widths)
  end.join( "\n" )
end

#value_to_str(value, width) ⇒ Object



19
20
21
# File 'lib/tableizer/text_table.rb', line 19

def value_to_str(value, width)
  "%#{width}s" % value.to_s.strip
end