Module: Forestify::InstanceMethods
- Defined in:
- lib/forestify.rb
Instance Method Summary collapse
- #children ⇒ Object
-
#initialize_position ⇒ Object
Initialize position fields Should be run only once.
- #is_leaf? ⇒ Boolean
- #is_node? ⇒ Boolean
- #parents ⇒ Object
- #update_positions_after_delete ⇒ Object
Instance Method Details
#children ⇒ Object
58 59 60 61 |
# File 'lib/forestify.rb', line 58 def children [] if is_leaf? self.class.where('left_position > ?', self.left_position).where('right_position < ?', self.right_position) end |
#initialize_position ⇒ Object
Initialize position fields Should be run only once
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/forestify.rb', line 15 def initialize_position # @parent = -1 is the option 'No parent' if @parent.nil? || @parent == "-1" # No parent has been specified, we need to add this leaf # to the right side of the last root node. last = self.class.order("right_position DESC").first self.left_position = (last.nil?) ? 0 : last.right_position + 1 self.right_position = self.left_position + 1 self.level = 0 else # Makes sure it's an integer @parent = @parent.to_i p = self.class.find(@parent) self.left_position = p.right_position self.right_position = self.left_position + 1 self.level = p.level + 1 # update nodes on the right hand side of parent self.class.update_all "left_position = left_position + 2", ['left_position > ?', p.right_position] self.class.update_all "right_position = right_position + 2", ['right_position > ?', p.right_position] # update parent p.update_attribute 'right_position', p.right_position + 2 end end |
#is_leaf? ⇒ Boolean
67 68 69 |
# File 'lib/forestify.rb', line 67 def is_leaf? !is_node? end |
#is_node? ⇒ Boolean
63 64 65 |
# File 'lib/forestify.rb', line 63 def is_node? (self.right_position - self.left_position) > 1 end |
#parents ⇒ Object
54 55 56 |
# File 'lib/forestify.rb', line 54 def parents self.class.where('left_position < ?', self.left_position).where('right_position > ?', self.right_position) end |
#update_positions_after_delete ⇒ Object
39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/forestify.rb', line 39 def update_positions_after_delete if is_node? # Update nodes to the right self.class.update_all "left_position = left_position - 2", ['left_position > ?', self.right_position] self.class.update_all "right_position = right_position - 2", ['right_position > ?', self.right_position] # Update children self.class.update_all "level = level - 1", ['left_position > ? AND right_position < ?', self.left_position, self.right_position] self.class.update_all "left_position = left_position - 1, right_position = right_position - 1", ['left_position > ? AND right_position < ?', self.left_position, self.right_position] else self.class.update_all "left_position = left_position - 2", ['left_position > ?', self.right_position] self.class.update_all "right_position = right_position - 2", ['right_position > ?', self.right_position] end end |