Class: AlignedTable
- Inherits:
-
Object
- Object
- AlignedTable
- Defined in:
- lib/aligned_table.rb
Constant Summary collapse
- VERSION =
"0.1.0"
Instance Attribute Summary collapse
-
#rows ⇒ Object
Returns the value of attribute rows.
-
#separator ⇒ Object
Returns the value of attribute separator.
-
#title ⇒ Object
Returns the value of attribute title.
Instance Method Summary collapse
- #column_lengths ⇒ Object
-
#initialize ⇒ AlignedTable
constructor
A new instance of AlignedTable.
- #render ⇒ Object
- #render_row(row, col_len) ⇒ Object
Constructor Details
#initialize ⇒ AlignedTable
Returns a new instance of AlignedTable.
6 7 8 |
# File 'lib/aligned_table.rb', line 6 def initialize @separator = " " end |
Instance Attribute Details
#rows ⇒ Object
Returns the value of attribute rows.
4 5 6 |
# File 'lib/aligned_table.rb', line 4 def rows @rows end |
#separator ⇒ Object
Returns the value of attribute separator.
4 5 6 |
# File 'lib/aligned_table.rb', line 4 def separator @separator end |
#title ⇒ Object
Returns the value of attribute title.
4 5 6 |
# File 'lib/aligned_table.rb', line 4 def title @title end |
Instance Method Details
#column_lengths ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/aligned_table.rb', line 25 def column_lengths columns = [] @rows.each do |row| row.each_with_index do |col, index| columns[index] ||= [] columns[index] << col end end columns.map! do |col| col.map { |x| x.to_s }.max_by(&:length).length end columns end |
#render ⇒ Object
10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/aligned_table.rb', line 10 def render col_len = column_lengths rows = @rows.map do |row| render_row(row, col_len) end max_row_length = rows.max_by(&:length).length if @title rows.unshift(" #@title ".center(max_row_length, "=")) end rows.join("\n") end |
#render_row(row, col_len) ⇒ Object
42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/aligned_table.rb', line 42 def render_row(row, col_len) columns = row.each_with_index.map do |col, index| if col.is_a?(Symbol) col.to_s * col_len[index] else if index == 0 col.to_s.rjust(col_len[index]) else col.to_s.ljust(col_len[index]) end end end columns.join(@separator) end |