I'm working on a project based on a Smalltalk paper, and a part of it
is to attempt to emulate changes in method lookup in Ruby as done in
Smalltalk. Namely, the paper mentions an alteration of the
no_such_method method in Smalltalk to have it do something before and
after each method execution. In Ruby, I have come as far as doing
#/usr/bin/env ruby
class Foo
def bar( baz, qux )
print baz << " is quite a " << qux << "\n"
end
def method_missing( aSymbol , *args )
print "before\n"
send( :bar, *args )
print "after\n"
end
end
However the results are not quite what I planned. When I use
quux = Foo.new
quux.bag( "Dog", "canine" )
(notice that I use an undefined method) I get
>ruby mmissing.rb
before
Dog is quite a canine
after
>Exit code: 0
Ok, not quite what I intended, but still useful, and certainly what
it's supposed to do. But when I do
quux = Foo.new
quux.bar( "Dog", "canine" )
I get
>ruby mmissing.rb
Dog is quite a canine
>Exit code: 0
Again, after some thinking it does what it is supposed to do (since
method bar is defined, method_missing never gets called). But it is
not what I intend it to do (eventually). What I thought would happen
is that when the object instance first gets the message for bar, bar
(which would be an instance of Method) would be still undefined, so
method_missing would get a message to look up bar, which is why I used
method_missing to start with.
So by now my first questions are:
- How does Ruby do its method lookup? I have spent a moderate time
reading the pickaxe an dlooking up subjects on Google regarding this,
but I couldn't find anything reliable (which doesn't mean that there
isn't - I might have missed a critical part). The closest I got was
some discussions on using method_missing. Pointers/Examples are
greatly appreciated.
- Could I use Object.method or Object.responds_to? to get the results I want?
- If it helps, I eventually would like to create a module that when
implemented does the "before method" and "after method" actions.
Thanks to anyone dedicating time to reading this. Cheers!
-CWS