Class: Matchi::BeAnInstanceOf
- Inherits:
-
Object
- Object
- Matchi::BeAnInstanceOf
- Defined in:
- lib/matchi/be_an_instance_of.rb
Overview
Type matcher that checks if an object is an exact instance of a specific class.
This matcher provides a secure way to verify an object’s exact type, ensuring it matches a specific class without including subclasses. It uses Ruby’s method binding mechanism to bypass potential method overrides, providing better protection against type check spoofing than standard instance_of? checks.
Instance Method Summary collapse
-
#initialize(expected) ⇒ BeAnInstanceOf
constructor
Initialize the matcher with (the name of) a class or module.
-
#match? { ... } ⇒ Boolean
Securely checks if the yielded object is an instance of the expected class.
-
#to_s ⇒ String
Returns a human-readable description of the matcher.
Constructor Details
#initialize(expected) ⇒ BeAnInstanceOf
Initialize the matcher with (the name of) a class or module.
69 70 71 72 73 74 75 |
# File 'lib/matchi/be_an_instance_of.rb', line 69 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
Securely checks if the yielded object is an instance of the expected class.
This method uses Ruby’s method binding mechanism to get the true class of an object, bypassing potential method overrides. While not completely foolproof, it provides better protection against type check spoofing than using regular method calls which can be overridden.
98 99 100 101 102 103 |
# File 'lib/matchi/be_an_instance_of.rb', line 98 def match? raise ::ArgumentError, "a block must be provided" unless block_given? actual_class = ::Object.instance_method(:class).bind_call(yield) expected_class == actual_class end |
#to_s ⇒ String
Returns a human-readable description of the matcher.
113 114 115 |
# File 'lib/matchi/be_an_instance_of.rb', line 113 def to_s "be an instance of #{@expected}" end |