Class: MdnQuery::Table
- Inherits:
-
Object
- Object
- MdnQuery::Table
- Defined in:
- lib/mdn_query/table.rb
Overview
A symmetric table with a nicely aligned textual representation.
The table automatically adjusts rows that are too small by padding them with empty strings.
Instance Attribute Summary collapse
-
#body ⇒ Array<Array<String>>
readonly
The body (list of rows) of the table.
-
#heading ⇒ Array<String>
readonly
The heading of the table.
-
#size ⇒ Fixnum
readonly
The number of columns in the table.
Instance Method Summary collapse
-
#add_row(row) ⇒ void
Adds a row to the body of the table.
-
#cols ⇒ Fixnum
Returns the number of columns in the table.
-
#initialize(heading, *rows) ⇒ MdnQuery::Table
constructor
Creates a new table.
-
#rows ⇒ Fixnum
Returns the number of rows in the body of the table.
-
#to_s ⇒ String
Returns the string representation of the table.
Constructor Details
#initialize(heading, *rows) ⇒ MdnQuery::Table
Creates a new table.
21 22 23 24 25 26 |
# File 'lib/mdn_query/table.rb', line 21 def initialize(heading, *rows) @heading = heading @size = heading.size @body = [] rows.each { |row| add_row(row) } end |
Instance Attribute Details
#body ⇒ Array<Array<String>> (readonly)
Returns the body (list of rows) of the table.
8 9 10 |
# File 'lib/mdn_query/table.rb', line 8 def body @body end |
#heading ⇒ Array<String> (readonly)
Returns the heading of the table.
11 12 13 |
# File 'lib/mdn_query/table.rb', line 11 def heading @heading end |
#size ⇒ Fixnum (readonly)
Returns the number of columns in the table.
14 15 16 |
# File 'lib/mdn_query/table.rb', line 14 def size @size end |
Instance Method Details
#add_row(row) ⇒ void
This method returns an undefined value.
Adds a row to the body of the table.
When the size of the row is smaller than the current table size, it is padded with empty strings to that size. When the size is greater than the current table size, the entire table is padded with empty strings to that size.
37 38 39 40 41 42 43 44 45 46 |
# File 'lib/mdn_query/table.rb', line 37 def add_row(row) if row.size < @size row.fill('', row.size...@size) elsif row.size > @size @heading.fill('', @size...row.size) @body.each { |r| r.fill('', @size...row.size) } @size = row.size end @body << row end |
#cols ⇒ Fixnum
Returns the number of columns in the table.
51 52 53 |
# File 'lib/mdn_query/table.rb', line 51 def cols @size end |
#rows ⇒ Fixnum
Returns the number of rows in the body of the table.
58 59 60 |
# File 'lib/mdn_query/table.rb', line 58 def rows @body.size end |
#to_s ⇒ String
Returns the string representation of the table.
This representation is a Markdown table that is aligned nicely, so that it is also easy to read in its raw format.
74 75 76 77 78 79 80 81 |
# File 'lib/mdn_query/table.rb', line 74 def to_s return '' if cols < 1 col_sizes = max_col_sizes str = heading_str(col_sizes) str << separator(col_sizes) str << body_str(col_sizes) str end |