Hi --
David said:
[...]
Basically, to know what's going to happen dynamically, you have to run
the program and send the messages.
It would be possible to define at writing time the entire range of
messages that an object will respond to. Here's how:
There are two kinds of messages to which an object responds by something
that is not a NoMethodError:
1) Those corresponding to defined instance methods.
2) Those that are handled in some way by method_missing.
That's every possible string you can sent to an object.
#1 is already well defined and thus handled by #respond_to?. So if we
could just define the range of messages recognized by method_missing, we
could have an object return the entire range of messages to which it
will respond.
Of course, we don't have standard support for that currently, but we
could (e.g. with some DSL) declare inside the class definition (e.g.
above the `def method_missing`) patterns to which method_missing would
respond.
So for example, in ActiveRecord::Base we would have something like:
responds_to /find_by_.+/
Thus `SomeRailsModel.respond_to? :find_by_name` would have the knowledge
it needs to return the correct answer: true.
That's a bit of a conversation-stopper

But I'll just observe that
"responding to a message" is really a kind of high-level, abstract way
of saying that the object has a method it can run whose name
corresponds to the message. That's not true of "find_by_name" in the
case of an ActiveRecord::Base subclass; there is no such method, and
the only way an object can handle the message is with method_missing,
which is not the same as the message itself being understood by the
object.
You could of course shoehorn find_by_* into respond_to? for AR
objects, if you don't mind, essentially, writing method_missing twice
(once for real, once as a kind of pseudo-static twin). But in the
general case, method_missing really means it's missing, and it's
handled at the time in ways that cannot be predicted or registered
with the system in advance. For example:
class C
def method_missing(m)
super unless rand(2).zero?
puts "I'm handing your message!"
end
end
c = C.new
Does c respond to "blah"?
In sum, the way it's engineered, with objects responding to certain
messages (in the sense of having corresponding methods), and
method_missing available to handle the missing ones, gives you more
latitude and flexibility than you'd be able to encapsulate in a
missing-method registry.
David
--
Q. What is THE Ruby book for Rails developers?
A. RUBY FOR RAILS by David A. Black (
http://www.manning.com/black)
(See what readers are saying!
http://www.rubypal.com/r4rrevs.pdf)
Q. Where can I get Ruby/Rails on-site training, consulting, coaching?
A. Ruby Power and Light, LLC (
http://www.rubypal.com)