Class: ElementFactory::Element

Inherits:
Object
  • Object
show all
Defined in:
lib/element_factory/element.rb

Constant Summary collapse

CONTENT_ATTRIBUTES =
{text: Elements::TextElement, inner_html: Elements::InnerHtmlElement}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, attributes_or_string = nil) ⇒ Element

Returns a new instance of Element.



7
8
9
10
11
12
13
14
15
16
17
# File 'lib/element_factory/element.rb', line 7

def initialize(name, attributes_or_string=nil)
  @name = name.to_s
  @attributes = coerce_attributes(attributes_or_string)

  CONTENT_ATTRIBUTES.each do |attribute, klass|
    if value = attributes[attribute]
      add_child klass.new(value)
      attributes.delete(attribute)
    end
  end
end

Instance Attribute Details

#attributesObject

Returns the value of attribute attributes.



3
4
5
# File 'lib/element_factory/element.rb', line 3

def attributes
  @attributes
end

#nameObject

Returns the value of attribute name.



3
4
5
# File 'lib/element_factory/element.rb', line 3

def name
  @name
end

Instance Method Details

#add_child(child) ⇒ Object Also known as: <<



28
29
30
# File 'lib/element_factory/element.rb', line 28

def add_child(child)
  children << child
end

#add_children(children) ⇒ Object



33
34
35
# File 'lib/element_factory/element.rb', line 33

def add_children(children)
  children.each {|child| add_child(child) }
end

#childrenObject



37
38
39
# File 'lib/element_factory/element.rb', line 37

def children
  @children ||= []
end

#html_attributesObject



24
25
26
# File 'lib/element_factory/element.rb', line 24

def html_attributes
  HtmlAttributes.new(self.attributes.dup)
end

#tag_endObject



46
47
48
# File 'lib/element_factory/element.rb', line 46

def tag_end
  (%|</%s>| % name).html_safe
end

#tag_middleObject



50
51
52
# File 'lib/element_factory/element.rb', line 50

def tag_middle
  (children.map(&:to_html).join).html_safe
end

#tag_startObject



41
42
43
44
# File 'lib/element_factory/element.rb', line 41

def tag_start
  tag_attributes = attributes.any?? " #{html_attributes}" : ""
  (%|<%s%s>| % [name, tag_attributes]).html_safe
end

#to_htmlObject Also known as: to_s



19
20
21
# File 'lib/element_factory/element.rb', line 19

def to_html
  tag_start + tag_middle + tag_end
end