Module: ActiveRecord::Acts::Tree::InstanceMethods
- Defined in:
- lib/active_record/acts/tree.rb
Instance Method Summary collapse
-
#ancestors ⇒ Object
Returns list of ancestors, starting from parent until root.
- #chain ⇒ Object
-
#childless ⇒ Object
Returns a flat list of all of the children under the current node which don’t have any children belonging to them (childless).
-
#descendants(node = self) ⇒ Object
Returns a flat list of the descendants of the current node.
- #leaf? ⇒ Boolean
-
#root ⇒ Object
Returns the root node of the tree.
- #root? ⇒ Boolean
-
#self_and_siblings(node = self) ⇒ Object
Returns all siblings and a reference to the current node.
-
#siblings ⇒ Object
Returns all siblings of the current node.
Instance Method Details
#ancestors ⇒ Object
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 |
#chain ⇒ Object
160 161 162 |
# File 'lib/active_record/acts/tree.rb', line 160 def chain [self.ancestors, self, self.descendants].flatten end |
#childless ⇒ Object
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
122 123 124 |
# File 'lib/active_record/acts/tree.rb', line 122 def leaf? children.length == 0 end |
#root ⇒ Object
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
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 |
#siblings ⇒ Object
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 |