Class: TimeSheet::TablePrinter
- Inherits:
-
Object
- Object
- TimeSheet::TablePrinter
- Defined in:
- lib/time_sheet/table_printer.rb
Instance Attribute Summary collapse
-
#options ⇒ Object
readonly
Returns the value of attribute options.
Instance Method Summary collapse
- #<<(row) ⇒ Object
- #flush ⇒ Object
- #format(value, width, last_column = false) ⇒ Object
- #generate ⇒ Object
-
#initialize(data = [], options = {}) ⇒ TablePrinter
constructor
A new instance of TablePrinter.
- #size(value) ⇒ Object
- #widths ⇒ Object
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 = [], = {}) = @data = data end |
Instance Attribute Details
#options ⇒ Object (readonly)
Returns the value of attribute options.
8 9 10 |
# File 'lib/time_sheet/table_printer.rb', line 8 def end |
Instance Method Details
#<<(row) ⇒ Object
10 11 12 |
# File 'lib/time_sheet/table_printer.rb', line 10 def <<(row) @data << row end |
#flush ⇒ Object
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 [:trim] ? str.strip : str end |
#generate ⇒ Object
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([: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 |
#widths ⇒ Object
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 |