Class: Parse::Constraint::RegularExpressionConstraint

Inherits:
Parse::Constraint 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 Attribute Summary

Attributes inherited from Parse::Constraint

#operand, #operation, #operator, #value

Instance Method Summary collapse

Methods inherited from Parse::Constraint

#as_json, constraint_keyword, create, formatted_value, #formatted_value, #initialize, #key, #precedence, #regex_unicode_option, register, #to_s

Constructor Details

This class inherits a constructor from Parse::Constraint

Instance Method Details

#buildHash

Builds the regex constraint with security validation.

Returns:

  • (Hash)

    the compiled constraint

Raises:

  • (ArgumentError)

    if the pattern is potentially dangerous (ReDoS)



1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
# File 'lib/parse/query/constraints.rb', line 1667

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

#likeRegularExpressionConstraint

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 1651

#regexRegularExpressionConstraint

Alias for #like



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

constraint_keyword :$regex