Class: Terminal::Table
- Inherits:
-
Object
- Object
- Terminal::Table
- Defined in:
- lib/terminal/table.rb
Instance Attribute Summary collapse
-
#column_widths ⇒ Object
Returns the value of attribute column_widths.
-
#headings ⇒ Object
Returns the value of attribute headings.
-
#rows ⇒ Object
Returns the value of attribute rows.
Instance Method Summary collapse
-
#initialize {|_self| ... } ⇒ Table
constructor
A new instance of Table.
- #recalculate_column_widths! ⇒ Object
- #to_s ⇒ Object
Constructor Details
#initialize {|_self| ... } ⇒ Table
Returns a new instance of Table.
38 39 40 41 42 43 44 |
# File 'lib/terminal/table.rb', line 38 def initialize @rows = [] @headings = [] @column_widths = [] yield self if block_given? recalculate_column_widths! end |
Instance Attribute Details
#column_widths ⇒ Object
Returns the value of attribute column_widths.
36 37 38 |
# File 'lib/terminal/table.rb', line 36 def column_widths @column_widths end |
#headings ⇒ Object
Returns the value of attribute headings.
35 36 37 |
# File 'lib/terminal/table.rb', line 35 def headings @headings end |
#rows ⇒ Object
Returns the value of attribute rows.
34 35 36 |
# File 'lib/terminal/table.rb', line 34 def rows @rows end |
Instance Method Details
#recalculate_column_widths! ⇒ Object
46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/terminal/table.rb', line 46 def recalculate_column_widths! if @rows.count > 0 (0...@rows.first.size).each do |col| @column_widths[col] = @rows.map { |row| row[col].to_s.twidth }.max end end if @headings.count > 0 (0...@headings.size).each do |col| @column_widths[col] = [@column_widths[col], @headings[col].twidth].max end end end |
#to_s ⇒ Object
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
# File 'lib/terminal/table.rb', line 60 def to_s result = '' = '+' + @column_widths.map { |w| '-' * (w + 2) }.join('+') + '+' + "\n" if @headings.count > 0 result += content = @headings.each_with_index.map { |grid, i| grid.to_s.tljust(@column_widths[i]) } result += '| ' + content.join(' | ') + " |\n" end result += @rows.each do |row| content = row.each_with_index.map { |grid, i| grid.to_s.tljust(@column_widths[i]) } result += '| ' + content.join(' | ') + " |\n" end result + end |