Class: Matchi::Satisfy

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

Overview

Custom matcher: passes when the given block, called with the actual value, returns true. The block must return true or false; any other value is an error, not a truthy pass.

Examples:

Matchi::Satisfy.new { |value| value > 41 }.match? { 42 } # => true

Instance Method Summary collapse

Constructor Details

#initialize {|actual| ... } ⇒ Satisfy

Returns a new instance of Satisfy.

Yield Parameters:

  • actual (Object) —

    the actual value

Yield Returns:

  • (Boolean)

Raises:

  • (ArgumentError) —

    when no block is given



16
17
18
19
20
# File 'lib/matchi/satisfy.rb', line 16

def initialize(&block)
  raise ::ArgumentError, "a block must be provided" unless block_given?

  @predicate = block
end

Instance Method Details

#match? ⇒ Boolean

Yield Returns:

  • (Object) —

    the actual value

Returns:

  • (Boolean)

Raises:

  • (ArgumentError) —

    when no block is given

  • (TypeError) —

    when the predicate returns something other than true or false



26
27
28
29
30
31
32
33
34
# File 'lib/matchi/satisfy.rb', line 26

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

  result = @predicate.call(yield)
  return result if true.equal?(result) || false.equal?(result)

  klass = ::Kernel.instance_method(:class).bind_call(result)
  raise ::TypeError, "the block must return true or false (got a #{Constant.label(klass)})"
end

#to_s ⇒ String

Returns:

  • (String)


37
38
39
# File 'lib/matchi/satisfy.rb', line 37

def to_s
  "satisfy &block"
end