Class: Qo::Matchers::HashMatcher

Inherits:
BaseMatcher show all
Defined in:
lib/qo/matchers/hash_matcher.rb

Overview

A Hash Matcher is a matcher that uses only keyword args to define a sequence of matches to perform against either an Object or another Hash.

In the case of a Hash matching against a Hash, it will compare the intersection of keys and match the values against eachother.

In the case of a Hash matching against an Object, it will treat the keys as method property invocations to be matched against the provided values.

All variants present in the BaseMatcher are present here, including ‘and’, ‘not’, and ‘or’.

Author:

  • baweaver

Instance Method Summary collapse

Methods inherited from BaseMatcher

#initialize

Constructor Details

This class inherits a constructor from Qo::Matchers::BaseMatcher

Instance Method Details

#call(target) ⇒ Proc[Any]

Used to match against a matcher made from Keyword Arguments (a Hash)

Parameters:

  • matchers (Hash[Any, respond_to?(:===)])

    Any key mapping to any value that responds to ‘===`. Notedly more satisfying when `===` does something fun.

Returns:

  • (Proc[Any])

    Hash -> Bool # Value matching against similar keys, will attempt to coerce to_s because JSON Object -> Bool # Uses keys as methods with public send to ‘===` match against the value



40
41
42
43
44
45
46
47
48
# File 'lib/qo/matchers/hash_matcher.rb', line 40

def call(target)
  return true if @keyword_matchers == target

  match_fn = target.is_a?(::Hash) ?
    Proc.new { |match_key, matcher| match_hash_value?(target, match_key, matcher)   } :
    Proc.new { |match_key, matcher| match_object_value?(target, match_key, matcher) }

  match_with(@keyword_matchers, &match_fn)
end

#to_procProc[Any]

Used to match against a matcher made from an Array, like:

Qo['Foo', 'Bar']

Parameters:

  • matchers (Array[respond_to?(===)])

    indexed tuple to match the target object against

Returns:

  • (Proc[Any])

    Array -> Bool # Tuple match against targets index Object -> Bool # Boolean public send



27
28
29
# File 'lib/qo/matchers/hash_matcher.rb', line 27

def to_proc
  Proc.new { |target| self.call(target) }
end