Class: MaRuKu::Out::HTML::HTMLElement

Inherits:
Object
  • Object
show all
Defined in:
lib/maruku/output/to_html.rb

Overview

A simple class to represent an HTML element for output.

Constant Summary collapse

SELF_CLOSING =

These elements have no children and should be rendered with a self-closing tag. It’s not an exhaustive list, but they cover everything we use.

Set.new %w[br hr img link meta]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, attr = {}, children = []) ⇒ HTMLElement

Returns a new instance of HTMLElement.



21
22
23
24
25
26
# File 'lib/maruku/output/to_html.rb', line 21

def initialize(name, attr={}, children=[])
  self.name = name
  self.attributes = attr || {}
  self.children = Array(children)
  children << yield if block_given?
end

Instance Attribute Details

#attributesObject

Returns the value of attribute attributes.



18
19
20
# File 'lib/maruku/output/to_html.rb', line 18

def attributes
  @attributes
end

#childrenObject

Returns the value of attribute children.



19
20
21
# File 'lib/maruku/output/to_html.rb', line 19

def children
  @children
end

#nameObject

Returns the value of attribute name.



17
18
19
# File 'lib/maruku/output/to_html.rb', line 17

def name
  @name
end

Instance Method Details

#<<(child) ⇒ Object



28
29
30
31
# File 'lib/maruku/output/to_html.rb', line 28

def <<(child)
  children << child if children
  self
end

#[](key) ⇒ Object



33
34
35
# File 'lib/maruku/output/to_html.rb', line 33

def [](key)
  attributes[key.to_s]
end

#[]=(key, value) ⇒ Object



37
38
39
# File 'lib/maruku/output/to_html.rb', line 37

def []=(key, value)
  attributes[key.to_s] = value
end

#add_class(class_name) ⇒ Object



41
42
43
# File 'lib/maruku/output/to_html.rb', line 41

def add_class(class_name)
  attributes['class'] = ((attributes['class']||'').split(' ') + [class_name]).join(' ')
end

#to_htmlObject Also known as: to_str, to_s



49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/maruku/output/to_html.rb', line 49

def to_html
  m = "<#{name}"
  attributes.each do |k, v|
    m << " #{k.to_s}=\"#{v.to_s}\""
  end

  if SELF_CLOSING.include? name
    m << " />"
  else
    content = children.map(&:to_s)
    m << ">" << content.join('') << "</#{name}>"
  end
end