forked from pupeno/carouselapps_table_builder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
table_builder.rb
126 lines (108 loc) · 2.88 KB
/
table_builder.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
58
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
module TableHelper
def table_for(objects, *args)
raise ArgumentError, "Missing block" unless block_given?
options = args.last.is_a?(Hash) ? args.pop : {}
html_options = options[:html]
builder = options[:builder] || TableBuilder
content_tag(:table, html_options) do
yield builder.new(objects || [], self, options)
end
end
class TableBuilder
include ::ActionView::Helpers::TagHelper
def initialize(objects, template, options)
raise ArgumentError, "TableBuilder expects an Enumerable object but found #{objects.inspect}" unless objects.respond_to? :each
@objects, @template, @options = objects, template, options
end
def head(*args)
if block_given?
concat(tag(:thead, options_from_hash(args), true))
yield
concat('</thead>')
else
@num_of_columns = args.size
content_tag(:thead,
content_tag(:tr,
args.collect { |c| content_tag(:th, c.html_safe)}.join('').html_safe
)
)
end
end
def head_r(*args)
raise ArgumentError, "Missing block" unless block_given?
options = options_from_hash(args)
head do
concat(tag(:tr, options, true))
yield
concat('</tr>')
end
end
def body(*args)
raise ArgumentError, "Missing block" unless block_given?
options = options_from_hash(args)
tbody do
@objects.each { |c| yield(c) }
end
end
def body_r(*args)
raise ArgumentError, "Missing block" unless block_given?
options = options_from_hash(args)
tbody do
@objects.each { |c|
concat(tag(:tr, options, true))
yield(c)
concat('</tr>'.html_safe)
}
end
end
def r(*args)
raise ArgumentError, "Missing block" unless block_given?
options = options_from_hash(args)
tr(options) do
yield
end
end
def h(*args)
if block_given?
concat(tag(:th, options_from_hash(args), true))
yield
concat('</th>')
else
content = args.shift
content_tag(:th, content, options_from_hash(args))
end
end
def d(*args)
if block_given?
concat(tag(:td, options_from_hash(args), true))
yield
concat('</td>')
else
content = args.shift
content_tag(:td, content, options_from_hash(args))
end
end
private
def options_from_hash(args)
args.last.is_a?(Hash) ? args.pop : {}
end
def concat(tag)
@template.safe_concat(tag)
""
end
def content_tag(tag, content, *args)
options = options_from_hash(args)
@template.content_tag(tag, content, options)
end
def tbody
concat('<tbody>')
yield
concat('</tbody>')
end
def tr options
concat(tag(:tr, options, true))
yield
concat('</tr>')
end
end
end