Class: Table
Overview
Copyright Steffie Dorn <[email protected]>, 2017 License: GNU GPLv3 (or later) <www.gnu.org/copyleft/gpl.html>
Instance Method Summary collapse
- #<<(row) ⇒ Object
- #[](row) ⇒ Object
- #[]=(row, x) ⇒ Object
-
#initialize(separator: "\t", alignment: :left) ⇒ Table
constructor
A new instance of Table.
- #render(out) ⇒ Object
- #to_s ⇒ Object
Constructor Details
#initialize(separator: "\t", alignment: :left) ⇒ Table
7 8 9 10 11 12 13 14 15 16 17 18 |
# File 'lib/muflax/table.rb', line 7 def initialize separator: "\t", alignment: :left @rows = [] @lengths = [] @separator = separator @just = case alignment when :left ; :ljust when :right ; :rjust when :center ; :center else raise "invalid alignment: #{alignment}" end end |
Instance Method Details
#<<(row) ⇒ Object
23 24 25 26 27 28 29 30 31 |
# File 'lib/muflax/table.rb', line 23 def <<(row) row.each.with_index do |x, i| l = @lengths[i] || 0 s = x.str_length @lengths[i] = s if s > l end @rows << row end |
#[](row) ⇒ Object
20 |
# File 'lib/muflax/table.rb', line 20 def [](row) ; @rows[row] ; end |
#[]=(row, x) ⇒ Object
21 |
# File 'lib/muflax/table.rb', line 21 def []=(row, x) ; @rows[row] = x ; end |
#render(out) ⇒ Object
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/muflax/table.rb', line 33 def render out @rows.each.with_index do |row, row_i| row.each.with_index do |elem, elem_i| len = @lengths[elem_i] next if len.nil? # align element based on how much it's internally longer than it appears aligned = if not elem.nil? elem_diff = elem.to_s.length - elem.str_length elem.send(@just, len + elem_diff) else " "*len end if elem_i == (row.size - 1) out.write(aligned.rstrip) else out.write(aligned) out.write(@separator) end end out.write("\n") unless row_i == (@rows.size - 1) end end |
#to_s ⇒ Object
58 59 60 |
# File 'lib/muflax/table.rb', line 58 def to_s render(StringIO.new).string end |