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

children[R]

The array of child nodes this node possesses

name[RW]

The name of this node

parent[RW]

The name of this node's parent

Public Class Methods

new(name) click to toggle source

Initializes the Node class

# File app/models/composite/node.rb, line 17
def initialize(name)
  @name = name
  @children = []
end

Public Instance Methods

<<(node)

Aliases the add method to '<<' allowing << to also set the child node's parent to itself

Alias for: add
[](index) click to toggle source

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
[]=(index, node) click to toggle source

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
add(node) click to toggle source

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
Also aliased as: <<
leaf?() click to toggle source

Indicates whether or not this node has any other child nodes – will likely rename this and implement two methods, one that returns Composite nodes and one that returns Leaf nodes

# File app/models/composite/node.rb, line 51
def leaf?
  children.empty?
end
remove(node) click to toggle source

Removes the child node from this node's children

# File app/models/composite/node.rb, line 32
def remove(node)
  @children.delete node
end