Module: Tablify

Defined in:
lib/tablify.rb

Class Method Summary collapse

Class Method Details

.table(array, opts = {}) ⇒ Object



2
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
28
29
30
31
32
33
# File 'lib/tablify.rb', line 2

def self.table(array, opts = {})
  headers = array.map(&:keys).flatten.uniq.sort

  if opts[:include]
    headers = headers & opts[:include]
  end
  if opts[:exclude]
    headers = headers - opts[:exclude]
  end

  column_widths = headers.map(&:length)

  array.each do |hash|
    headers.each_with_index do |header, i|
      l = hash[header].to_s.length
      if l > column_widths[i]
        column_widths[i] = l
      end
    end
  end

  lines = [horizontal_rule(column_widths)]
  lines << aligned_row(headers, column_widths)
  lines << horizontal_rule(column_widths)
  array.each do |row|
    row_elements = headers.map{|h| row[h]}
    lines << aligned_row(row_elements, column_widths)
  end
  lines << horizontal_rule(column_widths)

  lines.join("\n")
end