Class: SimpleNestedSet::Rebuild::FromPaths

Inherits:
Object
  • Object
show all
Defined in:
lib/simple_nested_set/rebuild/from_paths.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#numObject



6
7
8
# File 'lib/simple_nested_set/rebuild/from_paths.rb', line 6

def num
  @num ||= 0
end

Instance Method Details

#child?(node, child) ⇒ Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/simple_nested_set/rebuild/from_paths.rb', line 32

def child?(node, child)
  child && child.path =~ %r(^#{node.path}/)
end

#extract_children(node, nodes) ⇒ Object



26
27
28
29
30
# File 'lib/simple_nested_set/rebuild/from_paths.rb', line 26

def extract_children(node, nodes)
  children = nodes.select { |child| child?(node, child) }
  nodes.replace(nodes - children)
  children
end

#renumber(nodes) ⇒ Object



16
17
18
19
20
21
22
23
24
# File 'lib/simple_nested_set/rebuild/from_paths.rb', line 16

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) ⇒ Object



10
11
12
13
14
# File 'lib/simple_nested_set/rebuild/from_paths.rb', line 10

def run(nested_set)
  nodes = nested_set.order(:path).to_a
  renumber(nodes.dup)
  nodes.each(&:save)
end