Class: Matchi::BeAKindOf
- Inherits:
-
Object
- Object
- Matchi::BeAKindOf
- 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.
Instance Method Summary collapse
-
#initialize(expected) ⇒ BeAKindOf
constructor
Initialize the matcher with (the name of) a class or module.
-
#match? ⇒ Boolean
Checks if the yielded object is an instance of the expected class or one of its subclasses.
-
#to_s ⇒ String
Returns a string representing the matcher.
Constructor Details
#initialize(expected) ⇒ BeAKindOf
Initialize the matcher with (the name of) a class or module.
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.
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_s ⇒ String
Returns a string representing the matcher.
66 67 68 |
# File 'lib/matchi/be_a_kind_of.rb', line 66 def to_s "be a kind of #{@expected}" end |