Class: Ariel::Node

Inherits:
Object
  • Object
show all
Defined in:
lib/ariel/node.rb

Overview

A generic Node object. As an end user, you have no need to use this. All children are stored in a hash. #id and #type are undefined so they can be used freely as part of a Node::Structure

Direct Known Subclasses

Extracted, Structure

Defined Under Namespace

Classes: Extracted, Structure

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ Node

If the name is a string, it’s converted to a symbol. If not it’s just stored as is.



13
14
15
16
17
18
19
20
# File 'lib/ariel/node.rb', line 13

def initialize(name)
  @children={}
  if name.kind_of? String
@node_name=name.to_sym
			else
@node_name=name
			end
end

Instance Attribute Details

#childrenObject

Returns the value of attribute children.



9
10
11
# File 'lib/ariel/node.rb', line 9

def children
  @children
end

#node_nameObject

Returns the value of attribute node_name.



9
10
11
# File 'lib/ariel/node.rb', line 9

def node_name
  @node_name
end

#parentObject

Returns the value of attribute parent.



9
10
11
# File 'lib/ariel/node.rb', line 9

def parent
  @parent
end

Instance Method Details

#add_child(node) ⇒ Object

Given a Node object and a name, adds a child to the array of children, setting its parent as the current node, as well as creating an accessor method matching that name.



25
26
27
28
29
30
31
# File 'lib/ariel/node.rb', line 25

def add_child(node) 
  @children[node.node_name]=node
  node.parent = self
  # Trick stolen from OpenStruct
  meta = class << self; self; end
  meta.send(:define_method, node.node_name.to_s.to_sym) {@children[node.node_name]}
end

#each_descendant(include_self = false) ⇒ Object

Yields each descendant node. If passed true will also yield itself.



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/ariel/node.rb', line 34

def each_descendant(include_self=false)
  if include_self
    node_queue=[self]
  else
    node_queue=self.children.values
  end
  until node_queue.empty? do
    node_queue.concat node_queue.first.children.values
    yield node_queue.shift
  end
end

#inspectObject



46
47
48
49
50
# File 'lib/ariel/node.rb', line 46

def inspect
  ["#{self.class.name} - node_name=#{self.node_name.inspect};",
"parent=#{self.parent ? self.parent.node_name.inspect : nil.inspect };",
"children=#{self.children.keys.inspect};"].join ' '
end