Class: Mongory::Matchers::RegexMatcher
- Inherits:
-
AbstractMatcher
- Object
- AbstractMatcher
- Mongory::Matchers::RegexMatcher
- Defined in:
- lib/mongory/matchers/regex_matcher.rb
Overview
RegexMatcher implements the $regex
operator and also handles raw Regexp values.
This matcher checks whether a string record matches a regular expression. It supports both:
- Explicit queries using
:field.regex => /pattern/i
- Implicit literal Regexp values like
{ field: /pattern/i }
If a string is provided instead of a Regexp, it will be converted via Regexp.new(...)
.
This ensures consistent behavior for queries like :field.regex => "foo"
and :field.regex => /foo/
.
Constant Summary
Constants inherited from AbstractMatcher
AbstractMatcher::KEY_NOT_FOUND
Instance Attribute Summary
Attributes inherited from AbstractMatcher
Instance Method Summary collapse
-
#check_validity! ⇒ void
Ensures the condition is a valid regex pattern (Regexp or String).
-
#initialize(condition, context: Context.new) ⇒ RegexMatcher
constructor
Initializes the matcher with a regex pattern.
- #priority ⇒ Object
-
#raw_proc ⇒ Proc
Creates a raw Proc that performs the regex matching operation.
Methods inherited from AbstractMatcher
#cached_proc, #debug_proc, define_matcher, #match, #match?, #render_tree, #uniq_key
Methods included from Utils
included, included_classes, #is_blank?, #is_present?
Constructor Details
#initialize(condition, context: Context.new) ⇒ RegexMatcher
Initializes the matcher with a regex pattern. Converts string patterns to Regexp objects.
40 41 42 43 |
# File 'lib/mongory/matchers/regex_matcher.rb', line 40 def initialize(condition, context: Context.new) super @condition = Regexp.new(condition) if condition.is_a?(String) end |
Instance Method Details
#check_validity! ⇒ void
This method returns an undefined value.
Ensures the condition is a valid regex pattern (Regexp or String).
70 71 72 73 74 75 |
# File 'lib/mongory/matchers/regex_matcher.rb', line 70 def check_validity! return if @condition.is_a?(Regexp) return if @condition.is_a?(String) raise TypeError, '$regex needs a Regexp or string' end |
#priority ⇒ Object
62 63 64 |
# File 'lib/mongory/matchers/regex_matcher.rb', line 62 def priority @condition.source.start_with?('^') ? 8 : 20 end |
#raw_proc ⇒ Proc
Creates a raw Proc that performs the regex matching operation. The Proc checks if the record is a string that matches the pattern. Returns false for non-string inputs or if the match fails.
50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/mongory/matchers/regex_matcher.rb', line 50 def raw_proc condition = @condition Proc.new do |record| next false unless record.is_a?(String) record.match?(condition) rescue StandardError false end end |