Class: Tabloid::Row

Inherits:
Object
  • Object
show all
Defined in:
lib/tabloid/row.rb

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Row

Returns a new instance of Row.



2
3
4
5
6
7
8
9
10
11
12
13
# File 'lib/tabloid/row.rb', line 2

def initialize(*args)
  options = args.pop
  if args.first
    @data = args.first
  else
    @data = options[:data]
  end
  raise "Must supply data to .new when creating a new Row" unless @data

  @columns = options[:columns]
  raise "Must supply column information when creating a new Row" unless @columns
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object



57
58
59
60
61
62
63
# File 'lib/tabloid/row.rb', line 57

def method_missing(method, *args)
  if @columns.detect{|col| col.key == method}
    self[method]
  else
    super
  end
end

Instance Method Details

#[](key) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/tabloid/row.rb', line 41

def [](key)
  if @data.is_a? Array
    if key.is_a? Numeric
      @data[key]
    else
      index = @columns.index{|col| col.key == key}
      @data[index]
    end
  else
    if key.is_a? Numeric
      key = @columns[key].key
    end
    @data.send(key)
  end
end

#summarize(key, &block) ⇒ Object



37
38
39
# File 'lib/tabloid/row.rb', line 37

def summarize(key, &block)
  self[key]
end

#to_csvObject



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/tabloid/row.rb', line 16

def to_csv
  FasterCSV.generate do |csv|
    csv_array = []
    @columns.each_with_index do |col, index|
      next if col.hidden?
      val = self[col.key]
      csv_array << val
    end
    csv << csv_array
  end
end

#to_html(options = {}) ⇒ Object



28
29
30
31
32
33
34
35
# File 'lib/tabloid/row.rb', line 28

def to_html(options = {})
  html = Builder::XmlMarkup.new
  html.tr("class" => (options[:class] || "data")) do |tr|
    @columns.each_with_index do |col, index|
      tr.td(self[col.key], "class" => col.key) unless col.hidden?
    end
  end
end