Class: Tableizer::Table

Inherits:
Object
  • Object
show all
Defined in:
lib/tableizer/table.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cols_info, rows) ⇒ Table

Returns a new instance of Table.



17
18
19
20
# File 'lib/tableizer/table.rb', line 17

def initialize(cols_info, rows)
  @rows = rows
  @cols_info = cols_info
end

Instance Attribute Details

#cols_infoObject (readonly)

Returns the value of attribute cols_info.



15
16
17
# File 'lib/tableizer/table.rb', line 15

def cols_info
  @cols_info
end

#rowsObject (readonly)

Returns the value of attribute rows.



15
16
17
# File 'lib/tableizer/table.rb', line 15

def rows
  @rows
end

Class Method Details

.create(elems) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/tableizer/table.rb', line 22

def self.create(elems)
  rows = []
  cols_info = [] 
  gen = nil
  
  elems = [NullObject] if elems.first.nil?
  elems.each do |elem|
    yielded = yield elem
    rows << yielded.map{|col| col[1]}
    unless cols_info.empty? 
      yielded.zip(cols_info).each do |(row, col_info)|
        # Detect the type of the current column
        if col_info.col_type == NilClass && row[1].class != NilClass
          col_info.col_type = row[1].class
        end
      end
    else
      cols_info = yielded.map do |(header, val)|  
        ColInfo.new( header.to_s, val.class, [ header.to_s.strip.length, val.to_s.strip.length ].max )
      end
    end
  end
  self.new(cols_info,rows)
end

Instance Method Details

#to(table_type) ⇒ Object



47
48
49
50
51
# File 'lib/tableizer/table.rb', line 47

def to(table_type)
  mapper = {:csv => CsvTable,
            :text => TextTable}
  mapper.fetch(table_type).new.to_s(cols_info, rows)
end

#to_google_tableObject



68
69
70
# File 'lib/tableizer/table.rb', line 68

def to_google_table
  GoogleVisualization.render( rows, cols_info.map{|col| [col.col_type, col.header]} )
end

#to_htmlObject



53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/tableizer/table.rb', line 53

def to_html
  text = "<table border=\"1\">\n"
  text += "<thead>\n"
  text += "<tr>\n"
  text << cols_info.map{|a| "<th>#{a.header.strip}</th>" }.join("\n")
  text += "</tr>\n"
  text += "</thead>"
  text += "<tbody>"
  text << rows.map do |row| 
    "<tr>" + row.map{|col| "<td>#{col}</td>"}.join("\n") + "</tr>"
  end.join( "\n" )
  text += "</tbody>"
  text += "</table>"
end