Class: Table
- Inherits:
-
Object
- Object
- Table
- Defined in:
- lib/autograph/table.rb
Instance Attribute Summary collapse
-
#rows ⇒ Object
readonly
Returns the value of attribute rows.
Instance Method Summary collapse
- #<<(row_hash) ⇒ Object
- #column(name) ⇒ Object
-
#initialize(column_names) ⇒ Table
constructor
A new instance of Table.
- #max(name) ⇒ Object
- #to_html ⇒ Object
- #to_s ⇒ Object
Constructor Details
#initialize(column_names) ⇒ Table
Returns a new instance of Table.
4 5 6 7 |
# File 'lib/autograph/table.rb', line 4 def initialize(column_names) @column_names = column_names.map{|n| n.to_s.to_sym} @rows = [] end |
Instance Attribute Details
#rows ⇒ Object (readonly)
Returns the value of attribute rows.
2 3 4 |
# File 'lib/autograph/table.rb', line 2 def rows @rows end |
Instance Method Details
#<<(row_hash) ⇒ Object
17 18 19 20 |
# File 'lib/autograph/table.rb', line 17 def <<(row_hash) # Symbolize keys on the way in @rows << row_hash.inject({}){|x,y| x[y[0].to_s.to_sym] = y[1]; x} end |
#column(name) ⇒ Object
9 10 11 |
# File 'lib/autograph/table.rb', line 9 def column(name) @rows.map{|r| r[name.to_s.to_sym]} end |
#max(name) ⇒ Object
13 14 15 |
# File 'lib/autograph/table.rb', line 13 def max(name) @rows.map{|r| r[name.to_s.to_sym].to_i}.max end |
#to_html ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/autograph/table.rb', line 22 def to_html html = "<table>\n"; html << " <tr>\n" @column_names.each do |key| html << " <th>#{key}</th>\n" end html << " </tr>\n" rows.each do |r| html << " <tr>\n" @column_names.each do |key| html << " <td>#{r[key]}</td>\n" end html << " </tr>\n" end html << "</table>\n" html end |
#to_s ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/autograph/table.rb', line 40 def to_s width = 20 s = "" html = "-" html << "-"*@column_names.size*width; html << "\n" html << "|" @column_names.each do |key| html << sprintf("%#{width-2}s", key) html << " |" end html << "\n" html << "-" html << "-"*@column_names.size*width; html << "\n" rows.each do |r| html << "|" @column_names.each do |key| html << "#{sprintf("%#{width-2}s", r[key.to_sym])} |" end html << "\n" end html << "-" html <<"-"*@column_names.size*width; html end |