Module: Expectation::Matcher

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

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.



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/expectation/matcher.rb', line 50

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] => [Integer]
              e = expectation.first
              value.each_with_index { |v, idx| match!(v, e, idx) }
            else
              # Array as "object matching one of given expectations
              expectation.any? { |exp| _match?(value, exp) }
            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 }
          when Module
            if expectation == URI
              _match_uri?(value)
            else
              expectation === value
            end
          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)


37
38
39
40
41
42
# File 'lib/expectation/matcher.rb', line 37

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