Class: Klods::Node

Inherits:
Object
  • Object
show all
Defined in:
lib/klods/node.rb

Constant Summary collapse

VOID_TAGS =
%w[area base br col embed hr img input link meta source track wbr].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tag, attrs = {}, children = nil) ⇒ Node

Returns a new instance of Node.



14
15
16
17
18
# File 'lib/klods/node.rb', line 14

def initialize(tag, attrs = {}, children = nil)
  @tag = tag.to_s
  @attrs = normalize_attrs(attrs)
  @children = VOID_TAGS.include?(@tag) ? [] : flatten_children(children)
end

Instance Attribute Details

#attrsObject (readonly)

Returns the value of attribute attrs.



10
11
12
# File 'lib/klods/node.rb', line 10

def attrs
  @attrs
end

#childrenObject (readonly)

Returns the value of attribute children.



10
11
12
# File 'lib/klods/node.rb', line 10

def children
  @children
end

#tagObject (readonly)

Returns the value of attribute tag.



10
11
12
# File 'lib/klods/node.rb', line 10

def tag
  @tag
end

Instance Method Details

#to_sObject Also known as: to_str



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
# File 'lib/klods/node.rb', line 20

def to_s
  parts = ["<#{@tag}"]

  @attrs.each do |name, value|
    next if value.nil? || value == false

    if name == "class"
      cls = resolve_class(value)
      parts << %( class="#{escape_attr(cls)}") unless cls.empty?
    elsif name == "style"
      parts << %( style="#{escape_attr(style_to_s(value))}")
    elsif value == true
      parts << " #{name}"
    else
      parts << %( #{name}="#{escape_attr(value.to_s)}")
    end
  end

  if VOID_TAGS.include?(@tag)
    parts << " />"
    return parts.join
  end

  parts << ">"
  @children.each { |child| parts << child_to_s(child) }
  parts << "</#{@tag}>"
  parts.join
end