Module: Expectation::Matcher

Extended by:
Matcher
Included in:
Matcher
Defined in:
lib/expectation/matcher.rb

Overview

The Expectation::Matcher module implements the logic to match a value against a pattern.

Defined Under Namespace

Classes: Mismatch

Instance Method Summary collapse

Instance Method Details

#match!(value, expectation, info = nil) ⇒ Object

Matches a value against an expectation. Raises an Expectation::Mismatch if the expectation could not be matched.

The info parameter is used to add some position information to any Mismatch raised.



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/expectation/matcher.rb', line 48

def match!(value, expectation, info = nil)
  match = case expectation
          when :truish  then !!value
          when :fail    then false
          when Array    then
            if expectation.length == 1
              # Array as "array of elements matching an expectation"; for example
              # [1,2,3] => [Fixnum]
              e = expectation.first
              value.each_with_index { |v, idx| match!(v, e, idx) }
            else
              # Array as "object matching one of given expectations
              expectation.any? { |e| _match?(value, e) }
            end
          when Proc     then expectation.arity == 0 ? expectation.call : expectation.call(value)
          when Regexp   then value.is_a?(String) && expectation =~ value
          when :__block then value.call
          when Hash     then Hash === value &&
                             expectation.each { |key, exp| match! value[key], exp, key }
          else               expectation === value
  end

  return if match
  fail Mismatch.new(value, expectation, info)
end

#match?(value, expectation) ⇒ Boolean

Does a value match an expectation?

Returns:

  • (Boolean)


35
36
37
38
39
40
# File 'lib/expectation/matcher.rb', line 35

def match?(value, expectation)
  match! value, expectation
  true
rescue Mismatch
  false
end