lib/alf/renderer/text.rb in alf-0.10.0 vs lib/alf/renderer/text.rb in alf-0.10.1

- old
+ new

@@ -23,12 +23,13 @@ include Utils class Cell include Utils - def initialize(value) + def initialize(value, options = {}) @value = value + @options = options end def min_width @min_width ||= rendering_lines.inject(0) do |maxl,line| max(maxl,line.size) @@ -50,15 +51,15 @@ when NilClass "[nil]" when Symbol value.inspect when Float - "%.3f" % value + (@options[:float_format] || "%.3f") % value when Hash value.inspect when Alf::Iterator - Text::Renderer.render(value, "") + Text::Renderer.render(value, "", @options) when Array array_rendering(value) else value.to_s end @@ -82,12 +83,13 @@ end # class Cell class Row include Utils - def initialize(values) - @cells = values.collect{|v| Cell.new(v)} + def initialize(values, options = {}) + @cells = values.collect{|v| Cell.new(v, options)} + @options = options end def min_widths @cells.collect{|cell| cell.min_width} end @@ -110,13 +112,14 @@ end # class Row class Table include Utils - def initialize(records, attributes) + def initialize(records, attributes, options = {}) @header = Row.new(attributes) - @rows = records.collect{|r| Row.new(r)} + @rows = records.collect{|r| Row.new(r, options)} + @options = options end def render(buffer = "") sizes = @rows.inject(@header.min_widths) do |memo,row| memo.zip(row.min_widths).collect{|x,y| max(x,y)} @@ -134,24 +137,59 @@ buffer end end # class Table + class PrettyBuffer + + def initialize(out, options) + @out = out + @trim_at = options[:trim_at] + @page_at = options[:page_at] + @page_line = 0 + end + + def <<(str) + print_a_line trim(str) + self + end + + def trim(str) + return str unless (@trim_at && (str.length > @trim_at)) + trimmed = (str[0..(@trim_at-4)] + "...") + trimmed << "\n" if str =~ /\n$/ + trimmed + end + + def print_a_line(line) + @out << line + @page_line += 1 + do_wait if @page_at && (@page_line > @page_at) + end + + def do_wait + @out << "--- Press ENTER (or quit) ---\n" + throw :stop if $stdin.getc =~ /^[qQ](uit)?/ + @page_line = 0 + end + + end # class PrettyBuffer + protected def render(input, output) relation = input.to_a - attrs = relation.inject([]){|memo,t| - memo | t.keys - } - records = relation.collect{|t| - attrs.collect{|a| t[a]} - } - Table.new(records, attrs).render(output) + attrs = relation.inject([]){|memo,t| (memo | t.keys)} + records = relation.collect{|t| attrs.collect{|a| t[a]}} + table = Table.new(records, attrs, options) + buffer = options[:pretty] ? + PrettyBuffer.new(output, options) : output + catch(:stop){ table.render(buffer) } + output end - def self.render(input, output) - new(input).execute(output) + def self.render(input, output, options= {}) + new(input, options).execute(output) end ::Alf::Renderer.register(:text, "as a text table", self) end # class Renderer