Class: TimeSheet::TablePrinter

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data = [], options = {}) ⇒ TablePrinter

Returns a new instance of TablePrinter.



3
4
5
6
# File 'lib/time_sheet/table_printer.rb', line 3

def initialize(data = [], options = {})
  @options = options
  @data = data
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



8
9
10
# File 'lib/time_sheet/table_printer.rb', line 8

def options
  @options
end

Instance Method Details

#<<(row) ⇒ Object



10
11
12
# File 'lib/time_sheet/table_printer.rb', line 10

def <<(row)
  @data << row
end

#flushObject



14
15
16
# File 'lib/time_sheet/table_printer.rb', line 14

def flush
  @widths = nil
end

#format(value, width, last_column = false) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/time_sheet/table_printer.rb', line 41

def format(value, width, last_column = false)
  str = case value
    when Integer then value.to_s.rjust(width)
    when Date then value.strftime('%Y-%m-%d').rjust(width)
    when Time then value.strftime('%H:%M').rjust(width)
    when Float then ("%.2f" % value).rjust(width)
    when nil then ' ' * width
    else
      last_column ? value : value.ljust(width)
  end

  options[:trim] ? str.strip : str
end

#generateObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/time_sheet/table_printer.rb', line 18

def generate
  flush

  result = []
  @data.each do |row|
    output = if row == '-'
      widths.map{|w| '-' * w}
    else
      row.each_with_index.map do |r, i|
        format(r, widths[i], i == row.size - 1)
      end
    end
    result << output.join(options[:trim] ? '|' : ' | ')
  end
  result.join("\n")
end

#size(value) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
# File 'lib/time_sheet/table_printer.rb', line 55

def size(value)
  case value
    when nil then 0
    when Integer then value.to_s.size
    when Float then ("%.2f" % value).size
    when Date then 10
    when Time then 5
    else
      value.size
  end
end

#widthsObject



35
36
37
38
39
# File 'lib/time_sheet/table_printer.rb', line 35

def widths
  @widths ||= @data.first.each_with_index.map do |c, i|
    @data.map{|row| row == '-' ? 0 : size(row[i])}.max
  end
end