Class: ExcelTable

Inherits:
Object
  • Object
show all
Defined in:
lib/excel-data/excel_table.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(kind = "html") ⇒ ExcelTable

Returns a new instance of ExcelTable.



3
4
5
# File 'lib/excel-data/excel_table.rb', line 3

def initialize(kind="html")
  @kind = kind
end

Instance Attribute Details

#kindObject

Returns the value of attribute kind.



2
3
4
# File 'lib/excel-data/excel_table.rb', line 2

def kind
  @kind
end

Instance Method Details

#generate_table(items) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/excel-data/excel_table.rb', line 7

def generate_table(items)
  begin
    if items.first.class == Hash
    table = {header:thead_from_hash(items.first),
                body: tbody_from_hash(items)
              }
    elsif items.first.class == Array
    table = {
      header:thead_from_array(items.first),
      body: tbody_from_array(items)
    }
  else
    raise 'wrong data format'
  end

  rescue 
    puts 'Sorry, excel-data can only create tables from arrays of arrays or arrays of hashes atm'
  end
  return "<table>"+table[:header]+table[:body]+"</table>"
end

#generate_tbody(array_of_arrays) ⇒ Object



41
42
43
44
45
46
47
48
49
# File 'lib/excel-data/excel_table.rb', line 41

def generate_tbody(array_of_arrays)
      table_body = array_of_arrays.collect { |row| 
    "<tr>" + (row.collect{|cell| 
                "<td>"+cell.to_s+"</td>"
              }).join("\n")+"</tr>"
   }

   "<tbody>\n"+table_body.join("\n")+"</tbody>"
end

#tbody_from_array(array_of_arrays) ⇒ Object



36
37
38
39
# File 'lib/excel-data/excel_table.rb', line 36

def tbody_from_array(array_of_arrays)
  array_of_arrays.delete_at(0)
  generate_tbody(array_of_arrays)
end

#tbody_from_hash(array_of_hashes) ⇒ Object



32
33
34
35
# File 'lib/excel-data/excel_table.rb', line 32

def tbody_from_hash(array_of_hashes)

  generate_tbody(array_of_hashes.collect {|k| k.values.flatten })
end

#thead_from_array(array) ⇒ Object



51
52
53
# File 'lib/excel-data/excel_table.rb', line 51

def thead_from_array(array)
  "<thead>\n<tr>\n"+(array.collect {|k| "<th>"+k.to_s.titleize+"</th>" }.join("\n"))+"\n</tr>\n</thead>"
end

#thead_from_hash(hash) ⇒ Object



28
29
30
31
# File 'lib/excel-data/excel_table.rb', line 28

def thead_from_hash(hash)
  array = hash.keys.map {|k| k.to_s.titleize}
  thead_from_array(array)
end