Module: Tablelize

Defined in:
lib/tablelize.rb

Constant Summary collapse

VERSION =
"0.1.5"
SEPARATOR =
ENV.fetch("TABLELIZE_SEPARATOR", "   ")
HEADER_LINE =
ENV.fetch("TABLELIZE_HEADER_LINE", "")
ALIGN_STRING =
1
ALIGN_NUMBER =
2

Class Method Summary collapse

Class Method Details

.table(rows) ⇒ Object



9
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
36
37
38
39
40
41
42
# File 'lib/tablelize.rb', line 9

def self.table(rows)
  aligns = []
  widths = []
  rows.each_with_index do |row, line|
    row.each_with_index do |val, index|
      len = val.to_s.length
      widths[index] = len if widths[index].nil? || len > widths[index]

      if line > 0 and aligns[index] != ALIGN_STRING
        if val.is_a? Numeric
          aligns[index] = ALIGN_NUMBER
        else
          aligns[index] = ALIGN_STRING
        end
      end

    end
  end

  format = ""
  length = 0
  widths.each_with_index do |width, index|
    align = (aligns[index] == ALIGN_NUMBER) ? "" : "-"
    format = "#{format}%#{align}#{width}s#{SEPARATOR}"
    length += width
  end

  rows.each_with_index do |row, index|
    printf format.chomp(SEPARATOR) + "\n", *row
    if index == 0 and HEADER_LINE.length > 0
      puts HEADER_LINE * (length -1 + SEPARATOR.size * (rows.size - 1))
    end
  end
end