Class: RomanticText::Element

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(subject = nil, attributes = {}) ⇒ Element

Returns a new instance of Element.



5
6
7
8
9
10
11
# File 'lib/romantic_text/element.rb', line 5

def initialize(subject = nil, attributes = {})
  @name = pick_element_name(subject)
  @attributes = pick_id_and_classes(subject)
  merge_attributes!(attributes)
  @children = []
  @parent = nil
end

Instance Attribute Details

#parentObject

Returns the value of attribute parent.



12
13
14
# File 'lib/romantic_text/element.rb', line 12

def parent
  @parent
end

Instance Method Details

#<<(str) ⇒ Object Also known as: text, _



22
23
24
# File 'lib/romantic_text/element.rb', line 22

def <<(str)
  append_child HTMLNode.new(Utils.escape(str))
end

#>(element_or_str) ⇒ Object



28
29
30
31
32
33
34
# File 'lib/romantic_text/element.rb', line 28

def >(element_or_str)
  unless element_or_str.is_a?(Element) || element_or_str.is_a?(HTMLNode)
    element_or_str = HTMLNode.new(element_or_str)
  end
  append_child(element_or_str)
  element_or_str
end

#`(name) ⇒ Object



14
15
16
# File 'lib/romantic_text/element.rb', line 14

def `(name)
  Element.new(name).tap { |e| append_child(e) }
end

#append_child(element) ⇒ Object



54
55
56
57
58
# File 'lib/romantic_text/element.rb', line 54

def append_child(element)
  element.parent&.remove_child(element)
  element.parent = self
  @children.push(element)
end

#dangerous_raw_html(str) ⇒ Object



36
37
38
# File 'lib/romantic_text/element.rb', line 36

def dangerous_raw_html(str)
  append_child HTMLNode.new(str.to_s)
end

#h(name, attributes = {}, &block) ⇒ Object



18
19
20
# File 'lib/romantic_text/element.rb', line 18

def h(name, attributes = {}, &block)
  public_send(:`, name).render(attributes, &block)
end

#remove_child(element) ⇒ Object



60
61
62
63
64
65
# File 'lib/romantic_text/element.rb', line 60

def remove_child(element)
  return unless @children.include?(element)

  element.parent = nil
  @children.delete(element)
end

#render(attributes = {}, &block) ⇒ Object Also known as: []



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

def render(attributes = {}, &block)
  merge_attributes!(attributes)
  instance_eval(&block) if block_given?
  self
end

#to_sObject



47
48
49
50
51
52
# File 'lib/romantic_text/element.rb', line 47

def to_s
  inner = @children.map(&:to_s).join('')
  return inner if @name.nil?

  generate_tag(@name, @attributes, inner)
end