On 6/5/06, dblack / wobblini.net <dblack / wobblini.net> wrote:
> Hi --
>
> On Mon, 5 Jun 2006, Pat Maddox wrote:
>
> > Take this class:
> >
> > class Foo
> > def method_missing(m, *args)
> >   m.to_s
> > end
> > end
> >
> > irb(main):006:0> Foo.new.foo
> > => "foo"
> > irb(main):007:0> Foo.respond_to? :foo
> > => false
> >
> > This obviously just returns the name of any method that doesn't exist
> > for the object.  So if you can send the object any message and get a
> > result, why doesn't it respond_to those messages?
>
> Maybe because that would render #respond_to? essentially useless :-)
>
>
> David
>
> --
> David A. Black (dblack / wobblini.net)
> * Ruby Power and Light, LLC (http://www.rubypowerandlight.com)
>    > Ruby and Rails consultancy and training
> * Author of "Ruby for Rails" from Manning Publications!
>    > http://www.manning.com/black
>
>

In my example where the object responds to everything, sure.  It was
just an example though, and of course not every class is going to act
like this.

I guess the key is to write a predicate and stick it in both methods.

class Foo
 def method_missing(m, *args)
   valid_method?(m) ? m.to_s : super
 end

 def respond_to?(m)
  valid_method?(m)
 end

 private
 def valid_method?(m)
  true
 end
end

Of course it's not particularly useful here, but you could change
valid_method? to
def valid_method?(m)
  [ :foo, :bar ].include? m
 end

Guess I just thought Ruby would automatically pick it up.  However, I
don't see how it'd be able to, short of creating a copy of the object
in memory and calling the method on the object to see if it returns a
result.  If the copy gives a method missing error, then respond_to?
would return false.  Obviously it would suck to create a copy and
actually call the method just to see if an object responds to it.

Pat