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

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


113
114
115
116
# File 'lib/active_record/acts/tree.rb', line 113

def ancestors
  node, nodes = self, []
  nodes << node = node.parent until node.parent.nil? and return nodes
end

#chainObject



160
161
162
# File 'lib/active_record/acts/tree.rb', line 160

def chain
  [self.ancestors, self, self.descendants].flatten
end

#childlessObject

Returns a flat list of all of the children under the current node which don’t have any children belonging to them (childless)

node.childess # => [subchild1, subchild2]


168
169
170
# File 'lib/active_record/acts/tree.rb', line 168

def childless
  self.descendants.reject{|d| d.children.any?}
end

#descendants(node = self) ⇒ Object

Returns a flat list of the descendants of the current node.

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


149
150
151
152
153
154
155
156
157
158
# File 'lib/active_record/acts/tree.rb', line 149

def descendants(node=self)
  nodes = []
  nodes << node unless node == self

  node.children.each do |child|
    nodes += descendants(child)
  end

  nodes.compact
end

#leaf?Boolean

Returns:

  • (Boolean)


122
123
124
# File 'lib/active_record/acts/tree.rb', line 122

def leaf?
  children.length == 0
end

#rootObject

Returns the root node of the tree.



127
128
129
130
# File 'lib/active_record/acts/tree.rb', line 127

def root
  node = self
  node = node.parent until node.parent.nil? and return node
end

#root?Boolean

Returns:

  • (Boolean)


118
119
120
# File 'lib/active_record/acts/tree.rb', line 118

def root?
  parent == nil
end

#self_and_siblings(node = self) ⇒ Object

Returns all siblings and a reference to the current node.

subchild1.self_and_siblings # => [subchild1, subchild2]


142
143
144
# File 'lib/active_record/acts/tree.rb', line 142

def self_and_siblings(node = self)
  node.parent.present? ? node.parent.reload.children : node.class.roots
end

#siblingsObject

Returns all siblings of the current node.

subchild1.siblings # => [subchild2]


135
136
137
# File 'lib/active_record/acts/tree.rb', line 135

def siblings
  self_and_siblings - [self]
end