Class: Matchi::BeAKindOf

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

Overview

Type/class matcher for inheritance-aware type checking.

This matcher provides a clear way to check if an object is an instance of a specific class or one of its subclasses. It leverages Ruby’s native === operator which reliably handles class hierarchy relationships.

Examples:

Basic usage

require "matchi/be_a_kind_of"

matcher = Matchi::BeAKindOf.new(Numeric)
matcher.match? { 42 }     # => true
matcher.match? { 42.0 }   # => true
matcher.match? { "42" }   # => false

Instance Method Summary collapse

Constructor Details

#initialize(expected) ⇒ BeAKindOf

Initialize the matcher with (the name of) a class or module.

Examples:

require "matchi/be_a_kind_of"

Matchi::BeAKindOf.new(String)
Matchi::BeAKindOf.new("String")
Matchi::BeAKindOf.new(:String)

Parameters:

  • expected (Class, #to_s)

    The expected class name

Raises:

  • (ArgumentError)

    if the class name doesn’t start with an uppercase letter



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

def initialize(expected)
  @expected = String(expected)
  return if /\A[A-Z]/.match?(@expected)

  raise ::ArgumentError,
        "expected must start with an uppercase letter (got: #{@expected})"
end

Instance Method Details

#match?Boolean

Checks if the yielded object is an instance of the expected class or one of its subclasses.

This method uses the case equality operator (===) which provides a reliable way to check class hierarchy relationships in Ruby. When a class is the receiver of ===, it returns true if the argument is an instance of that class or one of its subclasses.

Examples:

Class hierarchy check

class Animal; end
class Dog < Animal; end

matcher = Matchi::BeAKindOf.new(Animal)
matcher.match? { Dog.new }    # => true
matcher.match? { Animal.new } # => true
matcher.match? { Object.new } # => false

Yield Returns:

  • (Object)

    the actual value to check

Returns:

  • (Boolean)

    true if the object is an instance of the expected class or one of its subclasses

Raises:

  • (ArgumentError)

    if no block is provided



57
58
59
60
61
# File 'lib/matchi/be_a_kind_of.rb', line 57

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

  expected_class === yield # rubocop:disable Style/CaseEquality
end

#to_sString

Returns a string representing the matcher.

Returns:

  • (String)

    a human-readable description of the matcher



66
67
68
# File 'lib/matchi/be_a_kind_of.rb', line 66

def to_s
  "be a kind of #{@expected}"
end