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]

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

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

#leaf?Boolean

Returns true if node has no children, false otherwise

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

Returns:

  • (Boolean)

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

def leaf?
  children.count == 0
end

#rootObject

Returns the root node of the tree.


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

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)

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

def root?
  parent.nil?
end

#self_and_ancestorsObject

Returns ancestors and current node itself.

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

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

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]

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

def self_and_children
  [self] + self.children
end

#self_and_siblingsObject

Returns all siblings and a reference to the current node.

subchild1.self_and_siblings # => [subchild1, subchild2]

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

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

#siblingsObject

Returns all siblings of the current node.

subchild1.siblings # => [subchild2]

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

def siblings
  self_and_siblings - [self]
end