Class: Tabbit

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

Instance Method Summary collapse

Constructor Details

#initialize(*headers) ⇒ Tabbit

When Tabbit.new is called, takes a undefined amount of headers to add to the table.



6
7
8
9
# File 'lib/tabbit.rb', line 6

def initialize(*headers)
  @table = [[]]
  headers.each { |h| @table[0].push h }
end

Instance Method Details

#add_line(*items) ⇒ Object



11
12
13
14
15
# File 'lib/tabbit.rb', line 11

def add_line(*items)
  line = []
  items.each { |i| line.push i }
  @table.push line
end

#to_sObject



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
# File 'lib/tabbit.rb', line 17

def to_s
  # Set instance variables for maximum length of each column
  @table[0].length.times do |n|
    self.instance_variable_set "@max_length_#{n}", 0.0
    # Finds the longest string in column n and assign it to @max_length_n.
    @table.each do |line|
      if line[n].length >  self.instance_variable_get("@max_length_#{n}")
        self.instance_variable_set "@max_length_#{n}", line[n].length.to_f
      end
    end
  end

  divider '=', @table, new_line: true

  # Write headers
  @table[0].length.times do |n|
    max_len = self.instance_variable_get("@max_length_#{n}")
    difference = max_len - @table[0][n].length + 2

    if @table[0][n] == @table[0].last
      puts '|' + (' ' * 2) + @table[0][n].bold.red + (' ' * difference) + '|'
    else
      print '|' + (' ' * 2) + @table[0][n].bold.red + (' ' * difference)
    end
  end

  divider '=', @table, new_line: true

  # Write the table body, amount of spaces depends on the maximum length of
  # that column.
  @table.length.times do |n|
    unless n == 0
      line = @table[n]
      line.length.times do |i|
        item = line[i]
        max_len2 = self.instance_variable_get("@max_length_#{i}")
        difference2 = max_len2 - item.length + 2
        if item == line.last
          puts '|' + (' ' * 2) + item + (' ' * difference2) + '|'
        else
          print '|' + (' ' * 2) + item + (' ' * difference2)
        end
      end
    end
  end

  divider '=', @table
end