Sha256: 2b7455f45d88143a29a54f1761088e7b19417d6ef1a07518255dc45765ccc458
Contents?: true
Size: 1.14 KB
Versions: 2
Compression:
Stored size: 1.14 KB
Contents
module RTUI class Table def initialize(title, items, *fields) @title = title @items = items @fields = fields end # http://gist.github.com/72234 def print return if @items.empty? puts @title #find max length for each field; start with the field names themselves @fields = @items.first.class.column_names unless @fields.any? max_len = Hash[*@fields.map {|f| [f, f.to_s.length]}.flatten] @items.each do |item| @fields.each do |field| len = item.send(field).to_s.length max_len[field] = len if len > max_len[field] end end border = '+-' + @fields.map {|f| '-' * max_len[f] }.join('-+-') + '-+' title_row = '| ' + @fields.map do |f| sprintf("%-#{max_len[f]}s", f.to_s.split("_")[0].capitalize) end.join(' | ') + ' |' puts border puts title_row puts border @items.each do |item| row = '| ' + @fields.map do |f| sprintf("%-#{max_len[f]}s", item.send(f)) end.join(' | ') + ' |' puts row end puts border puts "#{@items.length} items\n" end end end
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
rtui-0.2.2 | lib/rtui/table.rb |
rtui-0.2.1 | lib/rtui/table.rb |