Module: TreeStructure
- Extended by:
- ActiveSupport::Concern
- Defined in:
- lib/tree_structure.rb,
lib/tree_structure/version.rb
Defined Under Namespace
Classes: Error
Constant Summary collapse
- VERSION =
"0.1.1"
Instance Method Summary collapse
- #ancestors ⇒ Object
-
#depth ⇒ Object
root to child depth.
- #descendants ⇒ Object
- #leaf? ⇒ Boolean
- #leaves ⇒ Object
- #move_to_child_of(node) ⇒ Object
-
#path_to_root ⇒ Object
root to child path.
- #root? ⇒ Boolean
-
#siblings ⇒ Object
other node with the same parent.
- #subtree ⇒ Object
Instance Method Details
#ancestors ⇒ Object
24 25 26 27 28 29 30 31 32 |
# File 'lib/tree_structure.rb', line 24 def ancestors node, _ancestors = self, [] while node.parent _ancestors << node.parent node = node.parent end _ancestors end |
#depth ⇒ Object
root to child depth
58 59 60 61 62 63 64 65 |
# File 'lib/tree_structure.rb', line 58 def depth node, depth = self, 0 while node depth += 1 node = node.parent end depth end |
#descendants ⇒ Object
34 35 36 |
# File 'lib/tree_structure.rb', line 34 def descendants children.flat_map{|child| [child] + child.descendants} end |
#leaf? ⇒ Boolean
20 21 22 |
# File 'lib/tree_structure.rb', line 20 def leaf? children.empty? end |
#leaves ⇒ Object
67 68 69 70 71 72 73 |
# File 'lib/tree_structure.rb', line 67 def leaves if leaf? [self] else children.flat_map{|child| child.leaves} end end |
#move_to_child_of(node) ⇒ Object
75 76 77 |
# File 'lib/tree_structure.rb', line 75 def move_to_child_of(node) self.update(parent: node) end |
#path_to_root ⇒ Object
root to child path
48 49 50 51 52 53 54 55 |
# File 'lib/tree_structure.rb', line 48 def path_to_root node, path = self, [] while node path << node node = node.parent end path.reverse end |
#root? ⇒ Boolean
16 17 18 |
# File 'lib/tree_structure.rb', line 16 def root? parent_id.nil? end |
#siblings ⇒ Object
other node with the same parent
43 44 45 |
# File 'lib/tree_structure.rb', line 43 def siblings parent ? parent.children.where.not(id: self.id) : self.class.roots.where.not(id: self.id) end |
#subtree ⇒ Object
38 39 40 |
# File 'lib/tree_structure.rb', line 38 def subtree [self] + descendants end |