Class: SimpleNestedSet::Rebuild::FromParents
- Inherits:
-
Object
- Object
- SimpleNestedSet::Rebuild::FromParents
- Includes:
- SqlAbstraction
- Defined in:
- lib/simple_nested_set/rebuild/from_parents.rb
Instance Attribute Summary collapse
-
#num ⇒ Object
Returns the value of attribute num.
Instance Method Summary collapse
- #child?(node, child) ⇒ Boolean
- #direct_child?(node, child) ⇒ Boolean
- #extract_children(node, nodes) ⇒ Object
-
#initialize ⇒ FromParents
constructor
A new instance of FromParents.
- #renumber(nodes) ⇒ Object
- #run(nested_set, sort_order = :id) ⇒ Object
Methods included from SqlAbstraction
Constructor Details
#initialize ⇒ FromParents
Returns a new instance of FromParents.
8 9 10 |
# File 'lib/simple_nested_set/rebuild/from_parents.rb', line 8 def initialize @num = 0 end |
Instance Attribute Details
#num ⇒ Object
Returns the value of attribute num.
6 7 8 |
# File 'lib/simple_nested_set/rebuild/from_parents.rb', line 6 def num @num end |
Instance Method Details
#child?(node, child) ⇒ Boolean
47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/simple_nested_set/rebuild/from_parents.rb', line 47 def child?(node, child) if child.root? false elsif direct_child?(node, child) true else # recurse to find indirect children, # i.e. the child is one of the grandchildren of the node child?(node, child.parent) end end |
#direct_child?(node, child) ⇒ Boolean
59 60 61 |
# File 'lib/simple_nested_set/rebuild/from_parents.rb', line 59 def direct_child? node, child child.parent_id == node.id end |
#extract_children(node, nodes) ⇒ Object
41 42 43 44 45 |
# File 'lib/simple_nested_set/rebuild/from_parents.rb', line 41 def extract_children(node, nodes) children = nodes.select { |child| child?(node, child) } nodes.replace(nodes - children) children end |
#renumber(nodes) ⇒ Object
31 32 33 34 35 36 37 38 39 |
# File 'lib/simple_nested_set/rebuild/from_parents.rb', line 31 def renumber(nodes) until nodes.empty? node = nodes.shift node.lft = self.num += 1 num = renumber(extract_children(node, nodes)) node.rgt = self.num += 1 end num end |
#run(nested_set, sort_order = :id) ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/simple_nested_set/rebuild/from_parents.rb', line 12 def run(nested_set, sort_order = :id) order_columns = ([:parent_id] + Array[sort_order]).uniq.compact db_adapter = nested_set.first.class.connection.instance_variable_get('@config')[:adapter].to_sym order_clause = order_columns.map do |col| order_by(db_adapter, col) end nodes = if nested_set.respond_to?(:except) nested_set.except(:order).order(order_clause) else nested_set.reorder(order_clause) end.to_a renumber(nodes.dup) nodes.each(&:save) end |