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.



13
14
15
16
17
18
# File 'lib/maruku/output/to_html.rb', line 13

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.



10
11
12
# File 'lib/maruku/output/to_html.rb', line 10

def attributes
  @attributes
end

#childrenObject

Returns the value of attribute children.



11
12
13
# File 'lib/maruku/output/to_html.rb', line 11

def children
  @children
end

#nameObject

Returns the value of attribute name.



9
10
11
# File 'lib/maruku/output/to_html.rb', line 9

def name
  @name
end

Instance Method Details

#<<(child) ⇒ Object



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

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

#[](key) ⇒ Object



25
26
27
# File 'lib/maruku/output/to_html.rb', line 25

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

#[]=(key, value) ⇒ Object



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

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

#add_class(class_name) ⇒ Object



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

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

#to_htmlObject Also known as: to_str, to_s



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/maruku/output/to_html.rb', line 41

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