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.


  1. I don't know why Ruby doesn't handle it automatically, but I tend to wonder how often respond_to? is used in real code.

  2. At the very least, it can be useful when providing extension modules for DCI or other mixing-in purposes. It lets you see what the class you're extending responds to, so that you don't make too many far-reaching assumptions about its existing capabilities. Jim Gay gave a talk on DCI at Arlington Ruby Meetup, and made a followup blog post, where he discusses that. (I've been meaning to post a reply about making it sorta like Design By Contract.)


Note: Only a member of this blog may post a comment.