Class: LedgerWeb::Table

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(report) {|_self| ... } ⇒ Table

Returns a new instance of Table.

Yields:

  • (_self)

Yield Parameters:



6
7
8
9
10
11
# File 'lib/ledger_web/table.rb', line 6

def initialize(report)
  @report = report
  @decorators = []
  @attributes = {}
  yield self if block_given?
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



4
5
6
# File 'lib/ledger_web/table.rb', line 4

def attributes
  @attributes
end

Instance Method Details

#clear_decoratorsObject



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

def clear_decorators
  @decorators.clear
end

#decorate(decorator) ⇒ Object



13
14
15
# File 'lib/ledger_web/table.rb', line 13

def decorate decorator
  @decorators << decorator
end


21
22
23
24
25
26
# File 'lib/ledger_web/table.rb', line 21

def link href
  if_clause = href.delete(:if)
  href[href.keys.first] = LedgerWeb::Decorators::LinkDecorator.new(href.values.first)
  href[:if] = if_clause
  @decorators << href
end

#renderObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/ledger_web/table.rb', line 28

def render
  body_rows = []
  header_aligns = {}

  @report.each do |row|
    body_rows << row.each_with_index.map do |cell, cell_index|
      @decorators.each do |decorator|
        dec = decorator.dup
        if_clause = dec.delete(:if)
        matcher = dec.keys.first

        next unless matcher == :all || cell.title =~ matcher
        if if_clause
          next unless if_clause.call(cell, row)
        end
        cell = dec[matcher].decorate(cell, row)
        header_aligns[cell_index] = cell.align
      end

      style = cell.style.map { |key, val| "#{key}:#{val}"}.join(";")
      %Q{<td style="#{style}"><span class="pull-#{cell.align}">#{cell.text}</span></td>}
    end.join("")
  end

  body = "<tbody>" + body_rows.map { |r| "<tr>#{r}</tr>" }.join("") + "</tbody>"
  header = "<thead><tr>" + @report.fields.each_with_index.map { |f,i| "<th><span class=\"pull-#{header_aligns[i] || 'left'}\">#{f}</span></th>" }.join("") + "</tr></thead>"

  attrs = attributes.map { |key,val| "#{key}=\"#{val}\"" }.join(" ")
  "<table #{attrs}>#{header}#{body}</table>"
end