Module: Mongoid::Matcher::FieldExpression Private

Defined in:
lib/mongoid/matcher/field_expression.rb

Overview

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

Singleton module used for evaluating whether a given value in-memory matches an MSQL query expression related to a specific field.

Class Method Summary collapse

Class Method Details

.matches?(exists, value, condition) ⇒ true | false, Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns whether a value satisfies a condition.

Parameters:

  • exists (true | false)

    Whether the value exists.

  • value (Object)

    The value to check.

  • condition (Hash | Object)

    The condition predicate.

Returns:

  • (true | false)

    Whether the value matches.

  • (Boolean)


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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/mongoid/matcher/field_expression.rb', line 21

module_function def matches?(exists, value, condition)
  if condition.is_a?(Hash)
    condition.all? do |k, cond_v|
      k = k.to_s
      if k.start_with?('$')
        if %w($regex $options).include?(k)
          unless condition.key?('$regex')
            raise Errors::InvalidQuery, "$regex is required if $options is given: #{Errors::InvalidQuery.truncate_expr(condition)}"
          end

          if k == '$regex'
            if options = condition['$options']
              cond_v = case cond_v
              when Regexp
                BSON::Regexp::Raw.new(cond_v.source, options)
              when BSON::Regexp::Raw
                BSON::Regexp::Raw.new(cond_v.pattern, options)
              else
                BSON::Regexp::Raw.new(cond_v, options)
              end
            elsif String === cond_v
              cond_v = BSON::Regexp::Raw.new(cond_v)
            end

            FieldOperator.get(k).matches?(exists, value, cond_v)
          else
            # $options are matched as part of $regex
            true
          end
        else
          FieldOperator.get(k).matches?(exists, value, cond_v)
        end
      elsif Hash === value
        sub_values = Matcher.extract_attribute(value, k)
        if sub_values.length > 0
          sub_values.any? do |sub_v|
            Eq.matches?(true, sub_v, cond_v)
          end
        else
          Eq.matches?(false, nil, cond_v)
        end
      else
        false
      end
    end
  else
    case condition
    when ::Regexp, BSON::Regexp::Raw
      Regex.matches_array_or_scalar?(value, condition)
    else
      Eq.matches?(exists, value, condition)
    end
  end
end