Alle mercoledì 30 maggio 2007, Maurice Gladwell ha scritto:
> It seems Object#respond_to doesn't work for dynamically generated
> methods:
>
> SomeRailsModel.respond_to? 'find_by_name' #=> false
>
> 1. Is there some way to *really* check if an object will respond to a
> message, even if it will respond by a dynamically generated method?
>
> Right now, Object#respond_to? just doesn't do what it name promises: it
> doesn't check if an object responds to a message :foo, only if the
> object has a :foo method defined.
>
> Thanks,
> Maurice B. Gladwell

Are you sure find_by_name is a class method and not an instance method (i.e, 
do you call SomeRailsModel.find_by_name or something like 
SomeRailsModel.new.find_by_name)? I don't know Rails, so I may be wrong, but 
to me it seems that find_by_name is an instance method. If it is so, then you 
can't expect SomeRailsModel.respond_to? to return true. This has nothing to 
do with the method being dynamically generated. For instance,

Array.respond_to?(:select)

gives false, because select is an instance method.

Array.new.respond_to?(:select)

gives true, instead.

If you want to know whether a class has an *instance* method without first 
creating an instance of the class, you can call instance_methods on the 
class. It will return an array with the names of the methods instances of the 
class will have. For example:

Array.instance_methods
=>["select", "[]=", "inspect", "<<", ... ]

In your case, if find_by_name is an instance method, you can do this:

SomeRailsModel.instance_methods.include? 'find_by_name'

I hope this helps

Stefano