| Module | DBI::Utils::TableFormatter |
| In: |
lib/dbi/utils/tableformatter.rb
|
Formats a resultset in a textual table, suitable for printing.
Perform the formatting.
If a block is provided, output will be yielded each row if pagebreak is nil, otherwise it will be yielded when the output is complete.
# File lib/dbi/utils/tableformatter.rb, line 30
30: def self.ascii(header,
31: rows,
32: header_orient=:left,
33: rows_orient=:left,
34: indent=2,
35: cellspace=1,
36: pagebreak_after=nil,
37: output=STDOUT)
38:
39: if rows.size == 0 or rows[0].size == 0
40: output.puts "No rows selected"
41: return
42: end
43:
44: header_orient ||= :left
45: rows_orient ||= :left
46: indent ||= 2
47: cellspace ||= 1
48:
49: # pagebreak_after n-rows (without counting header or split-lines)
50: # yield block with output as param after each pagebreak (not at the end)
51:
52: col_lengths = (0...(header.size)).collect do |colnr|
53: [
54: (0...rows.size).collect { |rownr|
55: value = rows[rownr][colnr]
56: coerce(value).size
57: }.max,
58: header[colnr].size
59: ].max
60: end
61:
62: indent = " " * indent
63:
64: split_line = indent + "+"
65: col_lengths.each {|col| split_line << "-" * (col+cellspace*2) + "+" }
66:
67: cellspace = " " * cellspace
68:
69: output_row = proc {|row, orient|
70: output << indent + "|"
71: row.each_with_index {|c,i|
72: output << cellspace
73:
74: str = coerce(c)
75:
76: output << case orient
77: when :left then str.ljust(col_lengths[i])
78: when :right then str.rjust(col_lengths[i])
79: when :center then str.center(col_lengths[i])
80: end
81: output << cellspace
82: output << "|"
83: }
84: output << "\n"
85: }
86:
87: rownr = 0
88:
89: loop do
90: output << split_line + "\n"
91: output_row.call(header, header_orient)
92: output << split_line + "\n"
93: if pagebreak_after.nil?
94: rows.each {|ar| output_row.call(ar, rows_orient)}
95: output << split_line + "\n"
96: break
97: end
98:
99: rows[rownr,pagebreak_after].each {|ar| output_row.call(ar, rows_orient)}
100: output << split_line + "\n"
101:
102: rownr += pagebreak_after
103:
104: break if rownr >= rows.size
105:
106: yield output if block_given?
107: end
108:
109: end