Class: Mongory::Matchers::NinMatcher

Inherits:
AbstractMatcher show all
Defined in:
lib/mongory/matchers/nin_matcher.rb

Overview

NinMatcher implements the $nin (not in) operator.

It succeeds only if the record does not match any value in the condition array. If the record is an array, it fails if any element overlaps with the condition. If the record is a single value (including nil), it fails if it is included in the condition.

Examples:

Match single value

matcher = NinMatcher.build([1, 2, 3])
matcher.match?(4)        #=> true
matcher.match?(2)        #=> false

Match nil

matcher = NinMatcher.build([nil])
matcher.match?(nil)      #=> false

Match with array

matcher = NinMatcher.build([2, 4])
matcher.match?([1, 3, 5])  #=> true
matcher.match?([4, 5])     #=> false

See Also:

Constant Summary

Constants inherited from AbstractMatcher

AbstractMatcher::KEY_NOT_FOUND

Instance Attribute Summary

Attributes inherited from AbstractMatcher

#condition, #context

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from AbstractMatcher

#cached_proc, #debug_proc, define_matcher, #initialize, #match, #match?, #render_tree, #uniq_key

Methods included from Utils

included, included_classes, #is_blank?, #is_present?

Constructor Details

This class inherits a constructor from Mongory::Matchers::AbstractMatcher

Class Method Details

.build(condition, *args) ⇒ Object



27
28
29
30
31
32
33
# File 'lib/mongory/matchers/nin_matcher.rb', line 27

def self.build(condition, *args)
  return super unless condition.is_a?(Range)

  end_op = condition.exclude_end? ? '$gte' : '$gt'
  head, tail = [condition.first, condition.last].sort
  OrMatcher.build([{ '$lt' => head }, { end_op => tail }], *args)
end

Instance Method Details

#check_validity!void

This method returns an undefined value.

Ensures the condition is a valid array or range.

Raises:

  • (TypeError)

    if the condition is not an array nor a range



59
60
61
62
63
# File 'lib/mongory/matchers/nin_matcher.rb', line 59

def check_validity!
  return if @condition.is_a?(Array)

  raise TypeError, '$nin needs an array or range'
end

#priorityObject



51
52
53
# File 'lib/mongory/matchers/nin_matcher.rb', line 51

def priority
  1 + Math.log(@condition.size + 1, 1.5)
end

#raw_procProc

Creates a raw Proc that performs the not-in matching operation. The Proc checks if the record has no elements in common with the condition array.

Returns:

  • (Proc)

    A proc that performs not-in matching



39
40
41
42
43
44
45
46
47
48
49
# File 'lib/mongory/matchers/nin_matcher.rb', line 39

def raw_proc
  condition = Set.new(@condition)

  Proc.new do |record|
    if record.is_a?(Array)
      is_blank?(condition & record)
    else
      !condition.include?(record)
    end
  end
end