Module: Mongoid::Acts::NestedSet::OutlineNumber::ClassMethods

Defined in:
lib/mongoid_nested_set/outline_number.rb

Instance Method Summary collapse

Instance Method Details

#each_with_outline_number(objects, parent_number = nil) ⇒ Object

Iterates over tree elements and determines the current outline number in the tree. Only accepts default ordering, ordering by an other field than lft does not work. This method does not used the cached number field.

Example:

Category.each_with_outline_number(Category.root.self_and_descendants) do |o, level|


21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/mongoid_nested_set/outline_number.rb', line 21

def each_with_outline_number(objects, parent_number=nil)
  objects = Array(objects) unless objects.is_a? Array

  stack = []
  last_num = parent_number
  objects.each_with_index do |o, i|
    if i == 0 && last_num == nil && !o.root?
      last_num = o.parent.outline_number
    end

    if stack.last.nil? || o.parent_id != stack.last[:parent_id]
      # we are on a new level, did we descend or ascend?
      if stack.any? { |h| h[:parent_id] == o.parent_id }
        # ascend
        stack.pop while stack.last[:parent_id] != o.parent_id
      else
        # descend
        stack << {:parent_id => o.parent_id, :parent_number => last_num, :siblings => []}
      end
    end

    if o.root? && !roots_have_outline_numbers?
      num = nil
    else
      num = o.send(:build_outline_number,
        o.root? ? '' : stack.last[:parent_number],
        o.send(:outline_number_sequence, stack.last[:siblings])
      )
    end
    yield(o, num)

    stack.last[:siblings] << o
    last_num = num
  end
end

#roots_have_outline_numbers?Boolean

Do root nodes have outline numbers

Returns:

  • (Boolean)


66
67
68
# File 'lib/mongoid_nested_set/outline_number.rb', line 66

def roots_have_outline_numbers?
  false
end

#update_outline_numbers(objects, parent_number = nil) ⇒ Object



58
59
60
61
62
# File 'lib/mongoid_nested_set/outline_number.rb', line 58

def update_outline_numbers(objects, parent_number=nil)
  each_with_outline_number(objects, parent_number) do |o, num|
    o.update_attributes(outline_number_field_name => num)
  end
end