Class: Greentable::Table

Inherits:
Object
  • Object
show all
Defined in:
lib/greentable/greentable_table.rb

Instance Method Summary collapse

Constructor Details

#initialize(parent, records, opts) ⇒ Table

Returns a new instance of Table.



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

def initialize(parent, records, opts)
  @parent = parent
  @records = records
  defaults = Greentable.configuration.defaults.dup rescue {}
  @defaults_tr = deep_merge(defaults.delete(:tr), opts.delete(:tr))
  @defaults_th = deep_merge(defaults.delete(:th), opts.delete(:th))
  @defaults_td = deep_merge(defaults.delete(:td), opts.delete(:td))
  @opts = deep_merge(defaults, opts)

  #rows
  @tr_attributes = []

  #cols
  @th_attributes = []
  @th_html = []
  @td_attributes = []
  @td_html = []

end

Instance Method Details

#col(th = nil, opts = {}, &block) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/greentable/greentable_table.rb', line 33

def col(th = nil, opts = {}, &block)
  @th_html[@current_col] = th
  th_opts = opts.delete(:th) || {}
  td_opts = opts.delete(:td) || {}
  @th_attributes[@current_col] = deep_merge(th_opts, opts)
  @td_attributes[@current_col] = deep_merge(td_opts, opts)

  @td_html[@row_counter.i] ||= []
  @td_html[@row_counter.i][@current_col] = @parent.capture(&block)

  @current_col += 1
  return nil
end

#process(&block) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/greentable/greentable_table.rb', line 47

def process(&block)
  @row_counter = Counter.new(@records.size)

  @records.each do |record|
    @current_col = 0
    block.call(self, record)
    @row_counter.inc
  end

  self
end

#subrow(opts = {}, &block) ⇒ Object



27
28
29
30
31
# File 'lib/greentable/greentable_table.rb', line 27

def subrow(opts = {}, &block)
  return if capture_headers
  return if opts[:display_on] == :first && !@row_counter.first?
  return if opts[:display_on] == :last && !@row_counter.last?
end

#to_sObject



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/greentable/greentable_table.rb', line 59

def to_s
  ret = ""
  return ret if @td_html.empty?
  ret << "<table#{do_attributes(nil,@opts)}>"
  unless @th_html.compact.empty?
    ret << "<thead>"
    ret << "<tr#{do_attributes(nil, @defaults_tr)}>"
    @th_html.each_with_index do |th,col|
      ret << "<th#{do_attributes(nil, deep_merge(@defaults_th, @th_attributes[col]))}>#{th.is_a?(Proc) ? th.call.to_s : th}</th>"
    end
    ret << "</tr>"
    ret << "</thead>"
  end
  ret << "<tbody>"

  @row_counter.i.times do |row|
    ret << "<tr#{do_attributes(row, deep_merge(@defaults_tr, @tr_attributes[row]))}>"
    @td_html[row].each_with_index do |td,col|
      ret << "<td#{do_attributes(row, deep_merge(@defaults_td, @td_attributes[col]))}>#{td}</td>"
    end
    ret << "</tr>"
  end
  ret << "</tbody>"
  ret << "</table>"
  ret.html_safe
end