Module: Mongoid::Matcher::Bits Private

Included in:
BitsAllClear, BitsAllSet, BitsAnyClear, BitsAnySet
Defined in:
lib/mongoid/matcher/bits.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.

Mixin module included in bitwise expression matchers.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.operator_nameString

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 the name of the expression operator.

Returns:

  • (String)

    The operator name.



60
61
62
# File 'lib/mongoid/matcher/bits.rb', line 60

module_function def operator_name
  name.sub(/.*::/, '').sub(/\A(.)/) { |l| l.downcase }
end

Instance Method Details

#matches?(_exists, value, condition) ⇒ true | false

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 bitwise expression.

Parameters:

  • exists (true | false)

    Not used.

  • value (Object)

    The value to check.

  • condition (Numeric | Array<Numeric>)

    The expression predicate as a bitmask or position list.

Returns:

  • (true | false)

    Whether the value matches.



17
18
19
20
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
# File 'lib/mongoid/matcher/bits.rb', line 17

def matches?(_exists, value, condition)
  case value
  when BSON::Binary
    value = value.data.split('').map { |n| '%02x' % n.ord }.join.to_i(16)
  end
  case condition
  when Array
    array_matches?(value, condition)
  when BSON::Binary
    int_cond = condition.data.split('').map { |n| '%02x' % n.ord }.join.to_i(16)
    int_matches?(value, int_cond)
  when Integer
    if condition < 0
      raise Errors::InvalidQuery,
            "Invalid value for $#{operator_name} argument: negative integers are not allowed: #{condition}"
    end

    int_matches?(value, condition)
  when Float
    # Allow floats that are whole numbers (e.g. 50.0), but reject those
    # with a fractional part (e.g. 50.1) since bitwise ops require integers.
    int_cond = condition.to_i
    if int_cond == condition
      if int_cond < 0
        raise Errors::InvalidQuery,
              "Invalid value for $#{operator_name} argument: negative numbers are not allowed: #{condition}"
      end

      int_matches?(value, int_cond)
    else
      raise Errors::InvalidQuery,
            "Invalid type for $#{operator_name} argument: not representable as an integer: #{condition}"
    end
  else
    raise Errors::InvalidQuery, "Invalid type for $#{operator_name} argument: #{condition}"
  end
end