Class: Mongory::Matchers::InMatcher

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

Overview

InMatcher implements the $in operator.

It checks whether the record matches any value in the condition array. If the record is an array, it succeeds if any item overlaps with the condition. If the record is a single value (including nil), it matches if it is included in the condition.

Examples:

Match single value

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

Match nil

matcher = InMatcher.build([nil])
matcher.match?(nil)      #=> true

Match with array

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

See Also:

Constant Summary

Constants inherited from AbstractMatcher

AbstractMatcher::KEY_NOT_FOUND

Instance Attribute Summary

Attributes inherited from AbstractMatcher

#condition, #context

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

Instance Method Details

#check_validity!void

This method returns an undefined value.

Ensures the condition is an array or range.

Raises:

  • (TypeError)

    if condition is not an array nor a range



49
50
51
52
53
54
# File 'lib/mongory/matchers/in_matcher.rb', line 49

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

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

#raw_procProc

Creates a raw Proc that performs the in-matching operation. The Proc checks if any element of the record is in the condition array.

Returns:

  • (Proc)

    a Proc that performs the in-matching operation



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/mongory/matchers/in_matcher.rb', line 31

def raw_proc
  condition = @condition

  Proc.new do |record|
    if record.is_a?(Array)
      return false if condition.is_a?(Range)

      is_present?(condition & record)
    else
      condition.include?(record)
    end
  end
end