module Taxonomite::Tree
Public Instance Methods
is this an ancestor of another node?
# File lib/taxonomite/tree.rb, line 63 def ancestor_of?(nd) nd.is_ancestor?(self) end
return all ancestors of this node
# File lib/taxonomite/tree.rb, line 75 def ancestors a = Array.new self.parent._ancestors(a) unless self.parent.nil? return a end
is this a descendant of nd?
# File lib/taxonomite/tree.rb, line 69 def descendant_of?(nd) (self == nd) ? true : is_ancestor?(nd) end
return a chainable Mongoid criteria to get all descendants
# File lib/taxonomite/tree.rb, line 89 def descendants self.children.collect { |c| [c] + c.descendants }.flatten end
delete children; this *removes all of the children fromt he data base (and ensuing)
# File lib/taxonomite/tree.rb, line 116 def destroy_children children.destroy_all end
is the object an ancestor of nd?
# File lib/taxonomite/tree.rb, line 57 def is_ancestor?(nd) self.is_root? ? false : (self.parent == nd || self.parent.is_ancestor?(nd)) end
is this a leaf?
# File lib/taxonomite/tree.rb, line 45 def is_leaf? self.children.empty? end
is this a root node?
# File lib/taxonomite/tree.rb, line 39 def is_root? self.parent == nil end
get all of the leaves from this node downward @return [Array] an array of all of the leaves
# File lib/taxonomite/tree.rb, line 144 def leaves return [self] if self.is_leaf? self.children.collect { |c| c.leaves }.flatten end
move all children to the parent node !!! need to perform validations here?
# File lib/taxonomite/tree.rb, line 123 def move_children_to_parent children.each do |c| self.parent.children << c c.parent = self.parent # is this necessary? end end
nullifies all children's parent id (cuts link)
# File lib/taxonomite/tree.rb, line 107 def nullify_children children.each do |c| c.parent = nil c.save end end
find the root of this node
# File lib/taxonomite/tree.rb, line 51 def root self.is_root? ? self : self.parent.root end
return self + all ancestors of this node
# File lib/taxonomite/tree.rb, line 83 def self_and_ancestors return [self] + self.ancestors end
return a chainable Mongoid criteria to get self + all descendants
# File lib/taxonomite/tree.rb, line 101 def self_and_descendants [self] + self.descendants end
perform validation on whether this child is an acceptable child or not? the base_class must have a method 'validate_child?' to implement domain logic there
# File lib/taxonomite/tree.rb, line 133 def validate_child!(ch) raise InvalidChild.create(self, ch) if (ch == nil) raise CircularRelation.create(self, ch) if self.descendant_of?(ch) if base_class.method_defined? :validate_child self.validate_child(ch) # this should throw an error if not valid end end
Protected Instance Methods
to do - find a way to add a Mongoid criteria to return all of the nodes for this object descendants descendants_and_self ancestors ancestors_and_self
# File lib/taxonomite/tree.rb, line 164 def _ancestors(a) a << self self.parent._ancestors(a) unless self.parent.nil? end