class Patterns::Node
Admittedly, this was taken from Nick Slocum's very Ruby and very brilliant solution to the composite problem github.com/nslocum/design-patterns-in-ruby/tree/master/composite/tree Node -> Object
Represents a node that may contain any number of nodes, and any number of child nodes, forming a Tree-Like structure
Attributes
The array of child nodes this node possesses
The name of this node
The name of this node's parent
Public Class Methods
Initializes the Node class
# File app/models/composite/node.rb, line 17 def initialize(name) @name = name @children = [] end
Public Instance Methods
Aliases the add method to '<<' allowing << to also set the child node's parent to itself
Crazy ruby assignment trick that returns the child at the index it is assigned
# File app/models/composite/node.rb, line 37 def [](index) @children[index] end
Another crazy ruby assignment trick which allows a node to be replaced upon assignment while also marking the child node's parent as this node
# File app/models/composite/node.rb, line 42 def []=(index, node) replaced_child = @children[index] @children[index] = node replaced_child.parent = nil node.parent = self end
Adds a child node to this node's list of children
# File app/models/composite/node.rb, line 23 def add(node) @children << node node.parent = self end
Removes the child node from this node's children
# File app/models/composite/node.rb, line 32 def remove(node) @children.delete node end