Class: Mongory::Matchers::ExistsMatcher

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

Overview

ExistsMatcher implements the $exists operator, which checks whether a key exists.

It transforms the presence (or absence) of a field into a boolean value, then compares it to the condition using the == operator.

This matcher ensures the condition is strictly a boolean (true or false).

Examples:

matcher = ExistsMatcher.build(true)
matcher.match?(42)              #=> true
matcher.match?(KEY_NOT_FOUND)   #=> false

matcher = ExistsMatcher.build(false)
matcher.match?(KEY_NOT_FOUND)   #=> true

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 that the condition value is a valid boolean.

Raises:

  • (TypeError)

    if condition is not true or false



44
45
46
47
48
# File 'lib/mongory/matchers/exists_matcher.rb', line 44

def check_validity!
  return if [true, false].include?(@condition)

  raise TypeError, "$exists needs a boolean, but got #{@condition.inspect}"
end

#priorityObject



36
37
38
# File 'lib/mongory/matchers/exists_matcher.rb', line 36

def priority
  2
end

#raw_procProc

Creates a raw Proc that performs the existence check. The Proc checks if the record exists and compares it to the condition.

Returns:

  • (Proc)

    A proc that performs existence check with error handling



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

def raw_proc
  condition = @condition

  Proc.new do |record|
    # Check if the record is nil or KEY_NOT_FOUND
    # and compare it to the condition.
    (record != KEY_NOT_FOUND) == condition
  end
end