Class: Mutter::Table
Constant Summary collapse
- DefaultTable =
{ :delimiter => " ", :truncater => ".." }
- DefaultColumn =
{ :align => :left, :style => [] }
Instance Attribute Summary collapse
-
#columns ⇒ Object
Returns the value of attribute columns.
-
#rows ⇒ Object
Returns the value of attribute rows.
Instance Method Summary collapse
- #<<(row) ⇒ Object
- #column(options = {}) ⇒ Object
- #fixed? ⇒ Boolean
-
#initialize(options = {}, &blk) ⇒ Table
constructor
A new instance of Table.
- #print ⇒ Object
- #process(str, length = nil, align = :left, style = []) ⇒ Object
- #render ⇒ Object (also: #to_a)
- #to_s ⇒ Object
Constructor Details
#initialize(options = {}, &blk) ⇒ Table
Returns a new instance of Table.
14 15 16 17 18 19 |
# File 'lib/mutter/table.rb', line 14 def initialize = {}, &blk @columns, @rows = [], [] @options = DefaultTable.merge instance_eval(&blk) if (@fixed = block_given?) end |
Instance Attribute Details
#columns ⇒ Object
Returns the value of attribute columns.
3 4 5 |
# File 'lib/mutter/table.rb', line 3 def columns @columns end |
#rows ⇒ Object
Returns the value of attribute rows.
3 4 5 |
# File 'lib/mutter/table.rb', line 3 def rows @rows end |
Instance Method Details
#<<(row) ⇒ Object
27 28 29 30 31 32 33 34 |
# File 'lib/mutter/table.rb', line 27 def << row if row.size > @columns.size && fixed? raise ArgumentError, "row size is #{row.size} but I only have #{@columns.size} columns" else @rows << row end end |
#column(options = {}) ⇒ Object
23 24 25 |
# File 'lib/mutter/table.rb', line 23 def column = {} @columns << DefaultColumn.merge() end |
#fixed? ⇒ Boolean
21 |
# File 'lib/mutter/table.rb', line 21 def fixed?; @fixed end |
#print ⇒ Object
65 66 67 |
# File 'lib/mutter/table.rb', line 65 def print puts render end |
#process(str, length = nil, align = :left, style = []) ⇒ Object
69 70 71 72 73 74 75 76 77 78 79 |
# File 'lib/mutter/table.rb', line 69 def process str, length = nil, align = :left, style = [] length ||= str.length if str.length > length str[0...(length - @options[:truncater].length)] + @options[:truncater] else s = [Mutter.new.clear.process(str, style), ' ' * (length - str.length)] s.reverse! if align == :right s.join end end |
#render ⇒ Object Also known as: to_a
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/mutter/table.rb', line 36 def render # Create missing columns as needed (@rows.map {|r| r.size }.max - @columns.size).times do self.column end # Compute max column width @columns.each_with_index do |col, i| col[:_width] = @rows.map do |r| r[i].to_s.length end.max if @rows[i] end # print table @rows.map do |row| @columns.zip(row).map do |col, cell| process(cell.to_s || "", col[:width] || col[:_width], col[:align], col[:style]) end.join @options[:delimiter] end end |
#to_s ⇒ Object
61 62 63 |
# File 'lib/mutter/table.rb', line 61 def to_s render.join("\n") end |