While browsing the Ruby presentation of Srdjan Marinovic I came upon the following snippet, a great example of what makes Ruby such an exciting and productive language:
class Foo alias_method : old_say, :say_greeting def say_greeting(*args) log... old_say(*args) end end
The code above redirects calls to an existing method old_say in class Foo to a proxy method say_greeting, which logs the method call before it hands over to the original method.
This demonstrates how Ruby classes are inherently "open", in that they can be modified at runtime. That code sequence can be used to override both method calls to your own code as well as method calls to core library functions, or any other code.
Such language flexibility can be used for all kinds of dynamic programming funkiness; here it's used as a debugging tool. I haven't been doing much meta-programming yet, but it's feasible to create a simple debugging function that adds this proxy logging functionality to arbitrary method calls -- so that e.g. if you wanted to trace all HTTP requests in your application you could do something like this:
log_function_calls('Net::HTTP.get_response')
I'd love to hear about how a Java programmer might go about doing something equivalent. (He'd probably need a debugger.)
Comments
Comments are closed. You can contact me instead.