Module: ComfortableMexicanSofa::ActsAsTree::InstanceMethods

Defined in:
lib/comfortable_mexican_sofa/acts_as_tree.rb

Instance Method Summary collapse

Instance Method Details

#ancestorsObject

Returns list of ancestors, starting from parent until root.

subchild1.ancestors # => [child1, root]


58
59
60
61
62
# File 'lib/comfortable_mexican_sofa/acts_as_tree.rb', line 58

def ancestors
  node, nodes = self, []
  nodes << node = node.parent while node.parent
  nodes
end

#descendantsObject

Returns all children and children of children



65
66
67
68
69
70
71
72
# File 'lib/comfortable_mexican_sofa/acts_as_tree.rb', line 65

def descendants
  nodes = []
  self.children.each do |c|
    nodes << c
    nodes << c.descendants
  end
  nodes.flatten
end

#rootObject

Returns the root node of the tree.



75
76
77
78
79
# File 'lib/comfortable_mexican_sofa/acts_as_tree.rb', line 75

def root
  node = self
  node = node.parent while node.parent
  node
end

#root?Boolean

Checks if this node is a root

Returns:

  • (Boolean)


82
83
84
# File 'lib/comfortable_mexican_sofa/acts_as_tree.rb', line 82

def root?
  !self.parent
end

#self_and_siblingsObject

Returns all siblings and a reference to the current node.

subchild1.self_and_siblings # => [subchild1, subchild2]


96
97
98
# File 'lib/comfortable_mexican_sofa/acts_as_tree.rb', line 96

def self_and_siblings
  parent ? parent.children : self.class.roots
end

#siblingsObject

Returns all siblings of the current node.

subchild1.siblings # => [subchild2]


89
90
91
# File 'lib/comfortable_mexican_sofa/acts_as_tree.rb', line 89

def siblings
  self_and_siblings - [self]
end