Class: Markbridge::AST::Element

Inherits:
Node
  • Object
show all
Defined in:
lib/markbridge/ast/element.rb

Overview

Base class for all AST elements that can contain children. Elements form the structural nodes of the AST tree, while Text nodes are leaves.

Examples:

Creating an element with children

element = AST::Bold.new
element << AST::Text.new("hello")
element << AST::Text.new(" world")
element.children.size # => 1 (consecutive text nodes are merged)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeElement

Returns a new instance of Element.



17
18
19
# File 'lib/markbridge/ast/element.rb', line 17

def initialize
  @children = []
end

Instance Attribute Details

#childrenArray<Node> (readonly)

Returns the child nodes of this element.

Returns:

  • (Array<Node>)

    the child nodes of this element



15
16
17
# File 'lib/markbridge/ast/element.rb', line 15

def children
  @children
end

Instance Method Details

#<<(child) ⇒ Element

Add a child node to this element. Consecutive Text nodes are automatically merged for optimization.

Examples:

Adding children

element << AST::Text.new("hello")
element << AST::Bold.new

Parameters:

  • child (Node)

    the node to add as a child

Returns:

  • (Element)

    self for method chaining

Raises:

  • (TypeError)

    if child is not a Node instance



31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/markbridge/ast/element.rb', line 31

def <<(child)
  unless child.is_a?(Node)
    actual = child.nil? ? "nil" : child.class
    raise TypeError, "child must be a #{Markbridge::AST::Node} (got #{actual})"
  end

  if child.is_a?(Text) && children.last.is_a?(Text)
    @children.last.merge(child)
  else
    @children << child
  end

  self
end