Class: Matchi::BeAnInstanceOf

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

Overview

Exact type matcher: passes when the class of the actual value is the expected class itself, not a descendant.

The class of the actual value is read with Kernel#class bound to it, so an object that redefines class cannot lie, and a BasicObject is handled. The expected class can be given directly, or by name; see Constant.

Examples:

Matchi::BeAnInstanceOf.new(Integer).match? { 42 }   # => true
Matchi::BeAnInstanceOf.new(:Numeric).match? { 42 }  # => false

Instance Method Summary collapse

Constructor Details

#initialize(expected) ⇒ BeAnInstanceOf

Returns a new instance of BeAnInstanceOf.

Parameters:

  • expected (Class, String, Symbol) —

    the expected class, or its name

Raises:

  • (ArgumentError) —

    when expected is neither a Class nor a constant name



20
21
22
# File 'lib/matchi/be_an_instance_of.rb', line 20

def initialize(expected)
  @expected = Constant.normalize(expected, ::Class)
end

Instance Method Details

#match? ⇒ Boolean

Yield Returns:

  • (Object) —

    the actual value

Returns:

  • (Boolean)

Raises:

  • (ArgumentError) —

    when no block is given

  • (NameError) —

    when the name is not defined

  • (TypeError) —

    when the name does not resolve to a Class



29
30
31
32
33
34
35
# File 'lib/matchi/be_an_instance_of.rb', line 29

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

  actual_class = ::Kernel.instance_method(:class).bind_call(yield)

  Constant.resolve(@expected, ::Class).equal?(actual_class)
end

#to_s ⇒ String

Returns:

  • (String)


38
39
40
# File 'lib/matchi/be_an_instance_of.rb', line 38

def to_s
  "be an instance of #{Constant.label(@expected)}"
end