Module: Table

Defined in:
lib/helpers/table.rb

Class Method Summary collapse

Class Method Details

.new(headers, rows) ⇒ Object



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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/helpers/table.rb', line 3

def self.new(headers, rows)

  # Add 1 space padding to all values
  headers.map! do |header|
    header.prepend(" ")
    header += " "
    header
  end

  rows.map! do |row|
    row.map! do |value|
      # We don't want change the values of any variables passed in
      # We only prepend spaces for visual purposes, so let's modify a dup instead
      dupped_value = "" unless value
      dupped_value = value.dup if value
      dupped_value.prepend(" ")
      dupped_value += " "
      dupped_value
    end
  end

  column_length = {}
  headers.each_with_index do |value, index|
    column_length[index] = value.length unless column_length.key?(index)
    column_length[index] = value.length if value.length > column_length[index]
  end

  rows.each do |row|
    row.each_with_index do |value, index|
      column_length[index] = value.length unless column_length.key?(index)
      column_length[index] = value.length if value.length > column_length[index]
    end
  end

  table = "+"
  headers.each_with_index do |value, index|
    table += ("-" * column_length[index])
    table += "+"
  end
  table += "\n"

  table += "|"
  headers.each_with_index do |value, index|
    table += value + (" " * (column_length[index] - value.length))
    table += "|"
  end
  table += "\n"

  table += "+"
  headers.each_with_index do |value, index|
    table += "-" * column_length[index]
    table += "+"
  end
  table += "\n"

  rows.each do |row|
    table += "|"
    row.each_with_index do |value, index|
      # Remove color characters so they don't count towards string length
      value_for_length = value.gsub(/\e\[(\d+)m/, "")
      value_for_length = value_for_length.gsub(/\e\[(\d+);(\d+);(\d+)m/, "")
      num_spaces = (column_length[index] - value_for_length.length)
      table += value
      table += " " * num_spaces
      table += "|"
    end
    table += "\n"
  end

  table += "+"
  headers.each_with_index do |value, index|
    table += ("-" * column_length[index])
    table += "+"
  end
  table += "\n"

  table

end