Thursday, December 8, 2011

Ruby Geekery: Defining method_missing and respond_to at the same time

   Not all the code (or coding comments) I'd like to share with the world, is on my own blog.  Recently I made a comment I'd like to direct y'all to, over on Avdi Grimm's wondrous blog, Virtuous Code.  Long story short:
  • Ruby has this interesting mechanism called method_missing, whereby you can call a method that doesn't really exist, but method_missing will be called instead, recognize the name, and know what to do, often by pulling apart the name and acting on pieces.  (Yes, that's how a lot of the magic in Ruby on Rails works.)
  • There's also respond_to?, which you can use to ask if an object responds to a given message, which is "OO-geek talk" for whether it has a given method.   (Yes, "method" is basic OO terminology, but I mean hardcore OO-geek talk, the kind used by people who actually use languages like Smalltalk!)
  • The problem is, adding a method by having method_missing recognize it and perform the action, does not also add it to the things respond_to? knows about!  You could also manually add it to respond_to? at the same time, but that's not very DRY.  As some of us pointed out, that's exactly the kind of drudgery we expect Ruby to save us from.  (Sometimes you can have method_missing really add the method, in which case respond_to? should see it just fine, but that's another story.)

  • So Avdi wrote a blog post about what he came up with to do it automagically.

  • As I started reading his post, I envisioned a way to do it.  When I got to how he did it, it was a lot different.  His is suitable for dynamic situations where mine wasn't.

  • Later I came up with another way that is also dynamic, though some rough spots remain to be worked out.

  • Later still, I intend to come up with some further improvements.

  • Your feedback is solicited, whether there or (preferably) here.