Class: Tms::Table

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

Constant Summary collapse

ADJUST =
{:left => :ljust, :right => :rjust, :center => :center}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize {|_self| ... } ⇒ Table

Returns a new instance of Table.

Yields:

  • (_self)

Yield Parameters:

  • _self (Tms::Table)

    the object that the method was called on



9
10
11
12
# File 'lib/tms/table.rb', line 9

def initialize(&block)
  @cols, @rows = [], []
  yield self if block_given?
end

Instance Attribute Details

#colsObject

Returns the value of attribute cols.



7
8
9
# File 'lib/tms/table.rb', line 7

def cols
  @cols
end

#rowsObject

Returns the value of attribute rows.



7
8
9
# File 'lib/tms/table.rb', line 7

def rows
  @rows
end

Instance Method Details

#<<(row) ⇒ Object



19
20
21
# File 'lib/tms/table.rb', line 19

def <<(row)
  @rows << row
end

#col(name, color = nil, adjust = nil) ⇒ Object



15
16
17
# File 'lib/tms/table.rb', line 15

def col(name, color = nil, adjust = nil)
  @cols << {:name => name, :color => color, :adjust => ADJUST[adjust]}
end

#linesObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/tms/table.rb', line 23

def lines
  @cols.each_with_index do |col, i|
    col[:width] = ([col[:name]] + @rows.map{ |row| row[i] }).map(&:to_s).map(&:length).max
  end

  ([@cols.map{ |col| col[:name] }] + @rows).each_with_index.map do |line, i|
    line.zip(@cols).map do |val, col|
      width, color, adjust = col.values_at(:width, :color, :adjust)
      adjust ||= val.is_a?(Integer) ? :rjust : :ljust
      val_s = val.to_s.send(adjust, width)
      val_s = Colored.colorize(val_s, :foreground => color) if color
      val_s
    end.join(' ')
  end
end


39
40
41
# File 'lib/tms/table.rb', line 39

def print
  puts lines
end