Module: ActiveRecord::Acts::Tree::InstanceMethods

Defined in:
lib/plugins/acts_as_tree/lib/active_record/acts/tree.rb

Instance Method Summary collapse

Instance Method Details

#ancestorsObject

Returns list of ancestors, starting from parent until root.

subchild1.ancestors # => [child1, root]


61
62
63
64
65
# File 'lib/plugins/acts_as_tree/lib/active_record/acts/tree.rb', line 61

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

#descendants(depth = nil) ⇒ Object

Returns list of descendants.

root.descendants # => [child1, subchild1, subchild2]


70
71
72
73
74
75
76
77
# File 'lib/plugins/acts_as_tree/lib/active_record/acts/tree.rb', line 70

def descendants(depth=nil)
  depth ||= 0
  result = children.dup
  unless depth == 1
    result += children.collect {|child| child.descendants(depth-1)}.flatten
  end
  result
end

#rootObject

Returns the root node of the tree.



87
88
89
90
91
# File 'lib/plugins/acts_as_tree/lib/active_record/acts/tree.rb', line 87

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

#self_and_descendants(depth = nil) ⇒ Object

Returns list of descendants and a reference to the current node.

root.self_and_descendants # => [root, child1, subchild1, subchild2]


82
83
84
# File 'lib/plugins/acts_as_tree/lib/active_record/acts/tree.rb', line 82

def self_and_descendants(depth=nil)
  [self] + descendants(depth)
end

#self_and_siblingsObject

Returns all siblings and a reference to the current node.

subchild1.self_and_siblings # => [subchild1, subchild2]


103
104
105
# File 'lib/plugins/acts_as_tree/lib/active_record/acts/tree.rb', line 103

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

#siblingsObject

Returns all siblings of the current node.

subchild1.siblings # => [subchild2]


96
97
98
# File 'lib/plugins/acts_as_tree/lib/active_record/acts/tree.rb', line 96

def siblings
  self_and_siblings - [self]
end