Class: Tabbit

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

Instance Method Summary collapse

Constructor Details

#initialize(*headers) ⇒ Tabbit

Table initialized as an Array



8
9
10
11
# File 'lib/tabbit.rb', line 8

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

Instance Method Details

#add_line(*items) ⇒ Object

Adds line to @table in form of Array



14
15
16
17
18
# File 'lib/tabbit.rb', line 14

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

#to_sObject

Changes @table Array into format for printing to console.



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

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_len_of_column = self.instance_variable_get("@max_length_#{i}")
        difference2 = max_len_of_column - item.length + 2 # Spaces needed after item in column.
        if item == line.last
          puts '|' + (' ' * 2) + item + (' ' * difference2) + '|'
        else
          print '|' + (' ' * 2) + item + (' ' * difference2)
        end
      end
    end
  end

  divider '=', @table
end