Module: ActsAsTree::InstanceMethods

Defined in:
lib/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]


145
146
147
148
149
# File 'lib/acts_as_tree.rb', line 145

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

#descendantsObject

Returns list of descendants, starting from current node, not including current node.

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


154
155
156
157
158
# File 'lib/acts_as_tree.rb', line 154

def descendants
  children.each_with_object(children.to_a) {|child, arr|
    arr.concat child.descendants
  }.uniq
end

#leaf?Boolean

Returns true if node has no children, false otherwise

subchild1.leaf? # => true
child1.leaf?    # => false

Returns:

  • (Boolean)


214
215
216
# File 'lib/acts_as_tree.rb', line 214

def leaf?
  children.count == 0
end

#rootObject

Returns the root node of the tree.



168
169
170
171
172
# File 'lib/acts_as_tree.rb', line 168

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

#root?Boolean

Returns true if node has no parent, false otherwise

subchild1.root? # => false
root.root?      # => true

Returns:

  • (Boolean)


206
207
208
# File 'lib/acts_as_tree.rb', line 206

def root?
  parent.nil?
end

#self_and_ancestorsObject

Returns ancestors and current node itself.

subchild1.self_and_ancestors # => [subchild1, child1, root]


198
199
200
# File 'lib/acts_as_tree.rb', line 198

def self_and_ancestors
  [self] + self.ancestors
end

#self_and_childrenObject

Returns children (without subchildren) and current node itself.

root.self_and_children # => [root, child1]


191
192
193
# File 'lib/acts_as_tree.rb', line 191

def self_and_children
  [self] + self.children
end

#self_and_descendantsObject

Returns list of descendants, starting from current node, including current node.

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


163
164
165
# File 'lib/acts_as_tree.rb', line 163

def self_and_descendants
  [self] + descendants
end

#self_and_siblingsObject

Returns all siblings and a reference to the current node.

subchild1.self_and_siblings # => [subchild1, subchild2]


184
185
186
# File 'lib/acts_as_tree.rb', line 184

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

#siblingsObject

Returns all siblings of the current node.

subchild1.siblings # => [subchild2]


177
178
179
# File 'lib/acts_as_tree.rb', line 177

def siblings
  self_and_siblings - [self]
end