Module: Tins::Responding
- Included in:
- Object
- Defined in:
- lib/tins/responding.rb
Overview
A module that provides a convenient way to check if objects respond to specific methods.
The ‘responding?` method returns an object that can be used with the case/when construct to test if an object responds to certain methods. This is particularly useful for duck typing and implementing polymorphic behavior.
end
Instance Method Summary collapse
-
#responding?(*method_names) ⇒ Object
Returns a special object that can be used to test if objects respond to specific methods.
Instance Method Details
#responding?(*method_names) ⇒ Object
Returns a special object that can be used to test if objects respond to specific methods. The returned object implements ‘===` to perform the check.
This is particularly useful for duck typing and case/when constructs where you want to match against objects based on their interface rather than their class.
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/tins/responding.rb', line 42 def responding?(*method_names) Class.new do define_method(:to_s) do "Responding to #{method_names * ', '}" end alias inspect to_s define_method(:===) do |object| method_names.all? do |method_name| object.respond_to?(method_name) end end end.new end |