Class: Matchi::Predicate

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

Overview

Predicate matcher.

Instance Method Summary collapse

Constructor Details

#initialize(name, *args, **kwargs, &block) ⇒ Predicate

Initialize the matcher with a name and arguments.

Examples:

require "matchi/predicate"

Matchi::Predicate.new(:be_empty)

Parameters:

  • name (#to_s)

    A matcher name.

  • args (Array)

    A list of parameters.

  • kwargs (Hash)

    A list of keyword parameters.

  • block (Proc)

    A block of code.

Raises:

  • (::ArgumentError)


17
18
19
20
21
22
23
24
# File 'lib/matchi/predicate.rb', line 17

def initialize(name, *args, **kwargs, &block)
  @name = String(name)
  raise ::ArgumentError, "invalid predicate name format" unless valid_name?

  @args   = args
  @kwargs = kwargs
  @block  = block
end

Instance Method Details

#match?Boolean

Boolean comparison between the actual value and the expected value.

Examples:

require "matchi/predicate"

matcher = Matchi::Predicate.new(:be_empty)
matcher.match? { [] } # => true
require "matchi/predicate"

matcher = Matchi::Predicate.new(:have_key, :foo)
matcher.match? { { foo: 42 } } # => true

Yield Returns:

  • (#object_id)

    The actual value to receive the method request.

Returns:

  • (Boolean)

    A boolean returned by the actual value being tested.

Raises:

  • (::ArgumentError)


43
44
45
46
47
48
49
50
# File 'lib/matchi/predicate.rb', line 43

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

  value = yield.send(method_name, *@args, **@kwargs, &@block)
  return value if [false, true].include?(value)

  raise ::TypeError, "Boolean expected, but #{value.class} instance returned."
end

#to_sString

Returns a string representing the matcher.

Returns:

  • (String)

    a human-readable description of the matcher



55
56
57
58
59
60
61
62
63
# File 'lib/matchi/predicate.rb', line 55

def to_s
  (
    "#{@name.tr("_", " ")} " + [
      @args.map(&:inspect).join(", "),
      @kwargs.map { |k, v| "#{k}: #{v.inspect}" }.join(", "),
      (@block.nil? ? "" : "&block")
    ].reject { |i| i.eql?("") }.join(", ")
  ).strip
end