Class: Matchi::BeAKindOf
- Inherits:
-
Object
- Object
- Matchi::BeAKindOf
- Defined in:
- lib/matchi/be_a_kind_of.rb
Overview
Type matcher that checks if an object is an instance of a class or one of its subclasses.
This matcher provides a reliable way to verify object types while respecting Ruby’s inheritance hierarchy. It uses the case equality operator (===) which is Ruby’s built-in mechanism for type checking, ensuring consistent behavior with Ruby’s own type system.
Instance Method Summary collapse
-
#initialize(expected) ⇒ BeAKindOf
constructor
Creates a new type matcher for the specified class.
-
#match? { ... } ⇒ Boolean
Checks if the yielded object is an instance of the expected class or its subclasses.
-
#to_s ⇒ String
Returns a human-readable description of the matcher.
Constructor Details
#initialize(expected) ⇒ BeAKindOf
Creates a new type matcher for the specified class.
71 72 73 74 75 76 77 |
# File 'lib/matchi/be_a_kind_of.rb', line 71 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 its subclasses.
This method leverages Ruby’s case equality operator (===) which provides a reliable way to check class hierarchy relationships. When a class is the receiver of ===, it returns true if the argument is an instance of that class or one of its subclasses.
102 103 104 105 106 |
# File 'lib/matchi/be_a_kind_of.rb', line 102 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 human-readable description of the matcher.
116 117 118 |
# File 'lib/matchi/be_a_kind_of.rb', line 116 def to_s "be a kind of #{@expected}" end |