Class: Unify::HTML

Inherits:
Object
  • Object
show all
Defined in:
lib/unify/html.rb

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ HTML

Returns a new instance of HTML.



13
14
15
# File 'lib/unify/html.rb', line 13

def initialize(&block)
  @dom_stack = [{ :name => 'html', :properties => {}, :children => [] }]
end

Instance Method Details

#_(name, properties = {}, &block) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/unify/html.rb', line 17

def _(name, properties = {}, &block)
  element = { :name => name.to_s, :properties => properties, :children => [] }
  @dom_stack.last[:children] << element
  @dom_stack.push(element)
  if block_given?
    val = instance_eval(&block)
    if val.is_a?(String)
      @dom_stack.last[:inner_html] = val
    end
  end
  @dom_stack.pop
end

#to_html(element = @dom_stack.first) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/unify/html.rb', line 30

def to_html(element=@dom_stack.first)
  html = "<#{element[:name]}"
  for key in element[:properties].keys.sort
    html << %Q{ #{key}="#{element[:properties][key]}"}
  end
  if !element[:children].empty? || element[:inner_html]
    html << '>'
    for child in element[:children]
      html << to_html(child)
    end
    html << "#{element[:inner_html]}</#{element[:name]}>"
  else
    html << '/>'
  end
  html
end