Class: Html
- Inherits:
-
Object
show all
- Defined in:
- lib/rhtml.rb
Constant Summary
collapse
- INDENT =
' '
- VOID_TAGS =
%w{area base br col command embed hr img input keygen link meta param source track wbr}
Instance Attribute Summary collapse
Instance Method Summary
collapse
Constructor Details
#initialize(content = '', indent = 0, &b) ⇒ Html
7
8
9
10
11
|
# File 'lib/rhtml.rb', line 7
def initialize(content='', indent=0, &b)
@indent = 0
@content = content
@content << instance_eval(&b) if block_given?
end
|
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(tag_name, ps = {}, str = nil, &b) ⇒ Object
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
# File 'lib/rhtml.rb', line 13
def method_missing(tag_name, ps={}, str=nil, &b)
if ps.is_a? String
str, ps = ps, {}
end
tag_name = tag_name.to_s
if VOID_TAGS.include? tag_name
content << void_tag(tag_name, ps)
else
content << tag_open(tag_name, ps)
@indent += 1
if str
content << str << "\n"
elsif block_given?
ret = instance_eval &b
content << ret.to_s << "\n" unless ret.is_a?(self.class)
end
@indent -= 1
self.content << tag_close(tag_name)
end
self
end
|
Instance Attribute Details
#content ⇒ Object
Returns the value of attribute content.
2
3
4
|
# File 'lib/rhtml.rb', line 2
def content
@content
end
|
#indent ⇒ Object
Returns the value of attribute indent.
2
3
4
|
# File 'lib/rhtml.rb', line 2
def indent
@indent
end
|
Instance Method Details
#p(ps = {}, &b) ⇒ Object
conflict with global p method
39
40
41
|
# File 'lib/rhtml.rb', line 39
def p(ps={}, &b)
method_missing("p", ps, &b)
end
|
#properties(ps) ⇒ Object
43
44
45
|
# File 'lib/rhtml.rb', line 43
def properties ps
ps.map { |p| "#{p[0].to_s.gsub("_", "-")}='#{p[1].to_s}'" }.join(' ')
end
|
#tag_close(tag_name) ⇒ Object
55
56
57
|
# File 'lib/rhtml.rb', line 55
def tag_close tag_name
"#{INDENT * indent}</#{tag_name}>\n"
end
|
#tag_open(tag_name, ps = {}) ⇒ Object
47
48
49
50
51
52
53
|
# File 'lib/rhtml.rb', line 47
def tag_open tag_name, ps={}
if ps.empty?
"#{INDENT * indent}<#{tag_name}>\n"
else
"#{INDENT * indent}<#{tag_name} #{properties ps}>\n"
end
end
|
#to_s ⇒ Object
63
64
65
|
# File 'lib/rhtml.rb', line 63
def to_s
content
end
|
#void_tag(tag_name, ps = {}) ⇒ Object
59
60
61
|
# File 'lib/rhtml.rb', line 59
def void_tag tag_name, ps={}
"#{INDENT * indent}<#{tag_name} #{properties ps}/>\n"
end
|