class MultirootTree

Danny Pham 12/10/12

Attributes

children[R]
content[R]
parents[R]

Public Class Methods

new(content) click to toggle source
# File lib/multiroot_tree.rb, line 16
def initialize(content)
  @content = content
  @children = []
  @parents = []
end

Public Instance Methods

add_child(child) click to toggle source

add a child to the children array, instance variable

# File lib/multiroot_tree.rb, line 23
def add_child(child)
  if child.instance_of? MultirootTree
    @children << child unless @children.include? child
    child.add_parent(self) unless child.parents.include?(self)
  end
end
add_descendant_line(*descendants) click to toggle source

adds a list of MultirootTrees with each successive MultirootTree being the child of the previous

# File lib/multiroot_tree.rb, line 32
def add_descendant_line(*descendants)
  max = descendants.size
  num = 0
  first = self
  second = descendants[num]
  
  while (num < descendants.size)
    first.add_child(second)
    first = second
    second = descendants[num + 1]
    num += 1
  end
end
add_parent(parent) click to toggle source

adding parents is particularly necessary because any one node can have N parents, not just one

# File lib/multiroot_tree.rb, line 62
def add_parent(parent)
  @parents << parent unless @parents.include? parent
  parent.add_child(self) unless parent.children.include?(self)
end
add_parents(*parents) click to toggle source

adds immediate parents, not an ancestor line

# File lib/multiroot_tree.rb, line 68
def add_parents(*parents)
  parents.each do |parent| 
    self.add_parent(parent)
    parent.add_child(self) unless parent.children.include?(self)
  end
end
disowns(child) click to toggle source

severs tree connections going down descendant line

# File lib/multiroot_tree.rb, line 47
def disowns(child)
  if child.is_a? MultirootTree
    @children -= [child]
    child.emancipates_from(self) if child.parents.include?(self)
  end
end
emancipates_from(parent) click to toggle source

severs tree connections going up the ancestry

# File lib/multiroot_tree.rb, line 55
def emancipates_from(parent)
  @parents -= [parent]
  parent.disowns(self) if parent.children.include?(self) 
end
floor() click to toggle source

returns “youngest” children

# File lib/multiroot_tree.rb, line 87
def floor
  floor = []
  if @children.flatten.size == 0
    floor << MultirootTree.new(self.content)
  else
    @children.each {|child| floor << child.floor}
  end
  floor.flatten
end
inspect() click to toggle source

returns value of node

# File lib/multiroot_tree.rb, line 98
def inspect
  @content.inspect
end
roots() click to toggle source

returns roots/greatest parents

# File lib/multiroot_tree.rb, line 76
def roots
  roots ||= []
  if @parents.flatten.size == 0
    roots << self
  else
    @parents.each {|parent| roots << parent.roots}
  end
  roots.flatten
end