Class: TableOutput

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

Instance Method Summary collapse

Constructor Details

#initialize(cols, rows) ⇒ TableOutput

Returns a new instance of TableOutput.



3
4
5
6
7
8
# File 'lib/table_output.rb', line 3

def initialize(cols, rows)
  @cols = cols
  @rows = rows
  calc_sizes
  @ascii_encoding = Encoding.find("ASCII-8BIT")  
end

Instance Method Details

#calc_sizesObject



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/table_output.rb', line 10

def calc_sizes
  @sizes = []
  @align = []
  @cols.each_with_index do |col, index|
    @sizes[index] = col.to_s.length
    @align[index] = '-'

  end
  @rows.each do |row|
    row.each_with_index do |value, index|        
      row[index] = value = format_value(value, index)
      size = value.length
      if @sizes[index] < size
        @sizes[index] = size
      end
    end
  end
end

#format_value(value, index) ⇒ Object

FIXME - hard coded formating for floats and times



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/table_output.rb', line 30

def format_value(value, index)
  if value.class == String && value.encoding.to_s == "ASCII-8BIT" #timestamps and binary data
    a =  value.unpack("C" * value.size)
    value = "%x"*a.size % a
  elsif value.class == Float || value.class == BigDecimal
    value = "%.4f" % [value]
    @align[index] = "+"
  elsif value.class == BigDecimal
    value = value.to_s('F')
    @align[index] = "+"
  elsif value.class == Fixnum 
    @align[index] = "+"
  elsif value.class == Time
    value = value.
      strftime("%F %T").
      gsub(" 00:00:00", "")
    @align[index] = "+"
  end    
  #print "#{@cols[index]}\t#{value.class}\t#{value.to_s}\n"
  value.to_s
end

#to_sObject



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/table_output.rb', line 52

def to_s
  format = @sizes.each_with_index.map{|s, i| " %#{@align[i]}#{s}s "}.join("|")
  output = []

  separator = @sizes.map{|s| "-" * (s+2)}.join("+")
  separator = "+#{separator}+"
  output << ""
  output << separator
  output << "|#{format}|" % @cols
  output << separator
  @rows.each do |row|
    output << "|#{format}|" % row
  end
  output << separator
  output << "#{@rows.size} rows affected"
  output << ""
  output.join("\n")
end