Actions
Feature #17844
openSupport list of methods to test with respond_to?
Feature #17844:
Support list of methods to test with respond_to?
Status:
Open
Assignee:
-
Target version:
-
Description
Not sure whether this is a good idea at all, but I guess it doesn't hurt to put it up for debate.
The preferred way to check e.g. whether an argument is acceptable is by use of respond_to?:
# Don't
def notify(recipient)
raise ArgumentError unless recipient.instance_of?(User) || recipient.instance_of?(Follower)
...
end
# Do
def notify(recipient)
raise ArgumentError unless recipient.respond_to? :email
...
end
However, sometimes the tested object has to respond to more than one method in order to be acceptable:
def notify(recipient)
raise ArgumentError unless recipient.respond_to?(:email) && recipient.respond_to?(:name)
...
end
The refactored version doesn't look much nicer:
def notify(recipient)
raise ArgumentError unless %i(email name).reduce(true) do |memo, method|
memo &&= recipient.respond_to? method
end
...
The limiting factor here is respond_to? which only accepts one method as String or Symbol. How about extending it to accept an Array (of String or Symbol) as well?
Even nicer, but more complicated to implement due to the last and optional argument include_all:
What do you think?
Actions