Class: Matchi::Match

Inherits:
Object
  • Object
show all
Defined in:
lib/matchi/match.rb

Overview

Pattern matching matcher that checks if a value matches a regular expression.

This matcher verifies that a value matches a pattern using Ruby’s Regexp#match? method. It’s particularly useful for string validation, pattern matching, and text analysis. The matcher ensures secure pattern matching by requiring the pattern to respond to match?.

Examples:

Basic usage

matcher = Matchi::Match.new(/^test/)
matcher.match? { "test_string" }     # => true
matcher.match? { "other_string" }    # => false

Case sensitivity

matcher = Matchi::Match.new(/^test$/i)
matcher.match? { "TEST" }            # => true
matcher.match? { "Test" }            # => true
matcher.match? { "testing" }         # => false

Multiline patterns

matcher = Matchi::Match.new(/\A\d+\Z/m)
matcher.match? { "123" }             # => true
matcher.match? { "12.3" }            # => false

See Also:

Instance Method Summary collapse

Constructor Details

#initialize(expected) ⇒ Match

Initialize the matcher with a pattern.

Examples:

Match.new(/\d+/)           # Match digits
Match.new(/^test$/i)       # Case-insensitive match
Match.new(/\A\w+\Z/)       # Full string word characters

Parameters:

  • expected (#match?)

    A pattern that responds to match?

Raises:

  • (ArgumentError)

    if the pattern doesn’t respond to match?



42
43
44
45
46
# File 'lib/matchi/match.rb', line 42

def initialize(expected)
  raise ::ArgumentError, "expected must respond to match?" unless expected.respond_to?(:match?)

  @expected = expected
end

Instance Method Details

#match? { ... } ⇒ Boolean

Checks if the yielded value matches the expected pattern.

This method uses the pattern’s match? method to perform the comparison. The match is performed on the entire string unless the pattern specifically allows partial matches.

Examples:

matcher = Match.new(/^\d{3}-\d{2}-\d{4}$/)
matcher.match? { "123-45-6789" }   # => true
matcher.match? { "123456789" }     # => false

Yields:

  • Block that returns the value to check

Yield Returns:

  • (#to_s)

    The value to match against the pattern

Returns:

  • (Boolean)

    true if the value matches the pattern

Raises:

  • (ArgumentError)

    if no block is provided



67
68
69
70
71
# File 'lib/matchi/match.rb', line 67

def match?
  raise ::ArgumentError, "a block must be provided" unless block_given?

  @expected.match?(yield)
end

#to_sString

Returns a human-readable description of the matcher.

Examples:

Match.new(/^test/).to_s # => "match /^test/"

Returns:

  • (String)

    A string describing what this matcher verifies



81
82
83
# File 'lib/matchi/match.rb', line 81

def to_s
  "match #{@expected.inspect}"
end