Class: Matchi::Match

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

Overview

Regular expression matcher: passes when the actual value is a String or a Symbol that the expected Regexp matches. Any other actual value fails, as does a string with an invalid or incompatible encoding.

Only a Regexp is accepted as pattern: with a String pattern, String#match? would turn the actual value into the regular expression, handing the comparison to the code under test. Use Satisfy for other predicates.

Examples:

Matchi::Match.new(/^foo/).match? { "foobar" } # => true
Matchi::Match.new(/^foo/).match? { 42 }       # => false

Instance Method Summary collapse

Constructor Details

#initialize(expected) ⇒ Match

Returns a new instance of Match.

Parameters:

  • expected (Regexp) —

    the pattern

Raises:

  • (ArgumentError) —

    when expected is not a Regexp



19
20
21
22
23
# File 'lib/matchi/match.rb', line 19

def initialize(expected)
  raise ::ArgumentError, "expected must be a Regexp (got: #{expected.inspect})" unless ::Regexp === expected

  @expected = expected
end

Instance Method Details

#match? ⇒ Boolean

Yield Returns:

  • (Object) —

    the actual value

Returns:

  • (Boolean)

Raises:

  • (ArgumentError) —

    when no block is given



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/matchi/match.rb', line 28

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

  actual = yield
  return false unless ::String === actual || ::Symbol === actual

  # A plain copy: a subclass of String has no say in the comparison.
  string = ::String.new(::Symbol === actual ? actual.name : actual)
  return false unless string.valid_encoding?

  begin
    @expected.match?(string)
  rescue ::Encoding::CompatibilityError
    false
  end
end

#to_s ⇒ String

Returns:

  • (String)


46
47
48
# File 'lib/matchi/match.rb', line 46

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