Module: Mongoid::Acts::NestedSet::Validation

Included in:
Document::ClassMethods
Defined in:
lib/mongoid_nested_set/validation.rb

Instance Method Summary collapse

Instance Method Details

#all_roots_valid?Boolean

Wrapper for each_root_valid? that can deal with scope Warning: Very expensive! Do not use unless you know what you are doing.

Returns:

  • (Boolean)


38
39
40
41
42
43
44
45
46
# File 'lib/mongoid_nested_set/validation.rb', line 38

def all_roots_valid?
  if acts_as_nested_set_options[:scope]
    roots.group_by{|record| scope_field_names.collect{|field| record.send(field.to_sym)}}.all? do |scope, grouped_roots|
      each_root_valid?(grouped_roots)
    end
  else
    each_root_valid?(roots)
  end
end

#each_root_valid?(roots_to_validate) ⇒ Boolean

Returns:

  • (Boolean)


49
50
51
52
53
54
55
56
# File 'lib/mongoid_nested_set/validation.rb', line 49

def each_root_valid?(roots_to_validate)
  right = 0
  roots_to_validate.all? do |root|
    (root.left > right && root.right > right).tap do
      right = root.right
    end
  end
end

#left_and_rights_valid?Boolean

Warning: Very expensive! Do not use unless you know what you are doing.

Returns:

  • (Boolean)


13
14
15
16
17
18
19
20
21
22
23
# File 'lib/mongoid_nested_set/validation.rb', line 13

def left_and_rights_valid?
  all.detect { |node|
    node.send(left_field_name).nil? ||
      node.send(right_field_name).nil? ||
      node.send(left_field_name) >= node.send(right_field_name) ||
      !node.parent.nil? && (
        node.send(left_field_name) <= node.parent.send(left_field_name) ||
        node.send(right_field_name) >= node.parent.send(right_field_name)
    )
  }.nil?
end

#no_duplicates_for_fields?Boolean

Warning: Very expensive! Do not use unless you know what you are doing.

Returns:

  • (Boolean)


27
28
29
30
31
32
33
# File 'lib/mongoid_nested_set/validation.rb', line 27

def no_duplicates_for_fields?
  roots.group_by{|record| scope_field_names.collect{|field| record.send(field.to_sym)}}.all? do |scope, grouped_roots|
    [left_field_name, right_field_name].all? do |field|
      grouped_roots.first.nested_set_scope.only(field).group_by {|doc| doc.send(field)}.all? {|k, v| v.size == 1}
    end
  end
end

#valid?Boolean

Warning: Very expensive! Do not use unless you know what you are doing. This method is only useful for determining if the entire tree is valid

Returns:

  • (Boolean)


7
8
9
# File 'lib/mongoid_nested_set/validation.rb', line 7

def valid?
  left_and_rights_valid? && no_duplicates_for_fields? && all_roots_valid?
end