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.

Qo[name: /Foo/, age: 30..50].call({name: 'Foo', age: 42})
# => true

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.

```ruby

Qo[name: /Foo/, age: 30..50].call(Person.new('Foo', 42))

=> true


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

Author:

  • baweaver

Since:

  • 0.2.0

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) ⇒ Boolean

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

Parameters:

  • matchers (Hash[Any, #===])

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

Returns:

  • (Boolean)

    Result of the match

Since:

  • 0.2.0



49
50
51
52
53
54
55
56
57
# File 'lib/qo/matchers/hash_matcher.rb', line 49

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]

Wrapper around call to allow for invocation in an Enumerable function, such as:

people.select(&Qo[name: /Foo/, age: 20..40])

Returns:

  • (Proc[Any])

    Proc awaiting a target to match against

Since:

  • 0.2.0



38
39
40
# File 'lib/qo/matchers/hash_matcher.rb', line 38

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