Class: Parse::Constraint::RegularExpressionConstraint

Inherits:
Constraint
  • Object
show all
Defined in:
lib/parse/query/constraints.rb

Overview

Equivalent to the $regex Parse query operation. Requires that a field value match a regular expression.

q.where :field.like => /ruby_regex/i :name.like => /Bob/i

# Opt into Unicode-aware matching (Parse Server 8.3.0+ over REST, # MongoDB 6.1+ mongo-direct). The hash form compiles to the explicit # $regex/$options shape and adds the u flag: q.where :name.like => { value: /café/i, unicode: true } # Generates: "name": { "$regex": "café", "$options": "iu" }

Instance Method Summary collapse

Instance Method Details

#build ⇒ Hash

Builds the regex constraint with security validation.

Returns:

  • (Hash) —

    the compiled constraint

Raises:

  • (ArgumentError) —

    if the pattern is potentially dangerous (ReDoS)



2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
# File 'lib/parse/query/constraints.rb', line 2398

def build
  # Opt-in `{ value:, unicode: true }` form. Unlike the bare form (which
  # stringifies a Ruby Regexp to its inline-flag source, e.g.
  # "(?i-mx:Bob)"), this compiles to the explicit $regex/$options shape so
  # the `u` flag can be appended for Unicode-aware matching.
  if @value.is_a?(Hash)
    raw, unicode = regex_unicode_option(@value)
    pattern_str = raw.is_a?(Regexp) ? raw.source : raw.to_s
    options = +""
    options << "i" if raw.is_a?(Regexp) && raw.casefold?
    options << "u" if unicode

    Parse::RegexSecurity.validate!(pattern_str)

    return options.empty? ?
             { @operation.operand => { key => pattern_str } } :
             { @operation.operand => { key => pattern_str, :$options => options } }
  end

  value = formatted_value
  pattern_str = value.is_a?(Regexp) ? value.source : value.to_s
  options = value.is_a?(Regexp) && value.casefold? ? "i" : nil

  # Validate the regex pattern for ReDoS vulnerabilities
  Parse::RegexSecurity.validate!(pattern_str)

  if options
    { @operation.operand => { key => pattern_str, :$options => options } }
  else
    { @operation.operand => { key => pattern_str } }
  end
end

#like ⇒ RegularExpressionConstraint

A registered method on a symbol to create the constraint. Maps to Parse operator "$regex".

Examples:

q.where :field.like => /ruby_regex/i

Returns:



# File 'lib/parse/query/constraints.rb', line 2382

#regex ⇒ RegularExpressionConstraint

Alias for #like



2391
# File 'lib/parse/query/constraints.rb', line 2391

constraint_keyword :$regex