Monday, March 9, 2009

Hard Stuff in Ruby- Part 6: Method Missing

What is method_missing? It's a way of enabling your code to figure out what to do when a method is called that isn't defined.

Under normal conditions, this will throw a NoMethodError:

"a string".some_method

Throw this in:

String.class_eval "def method_missing(methId); puts methId; end;"

Now "a string".some_method returns "some_method".

Sweet. How is this useful? It might be irresponsible to throw one of these in everywhere you can, because everything could inexplicably without some error handling. Nonetheless, basically, you get a nice system for handling some big chunks of the unknown.

One of the areas where I'd thought it might be useful is with a DSL for music. Say you're handling an arbitrary amount of accidentals with a note. g.b makes sense. So you define a .b method for notes. Okay. What about double b? g.b.b should be fine. Looks a bit odd. g.b(2), that is awkward, and it might be best to reserve a numerical param for other data such as octave, chord type, etc. An options hash would do the trick, but it could look a little more natural to a musician if it was g.bb, right? THAT is what method_missing can do for you. Interpret the number of flat symbols and pass that off to the function that does the work. Neat

Okay. So that's it for the Hard Stuff in Ruby list. I don't think that this series demonstrates or necessarily provokes brilliance, but I hadn't seen a list of hard topics, with just basic explanations anywhere else. The docs can be incomplete, and most blogs usually focus on more "interesting" (inaccessible to mortals) applications of different topics. There are some exceptions, but a good deal of what I've seen.

Getting over the hump is crucial though. It's the difference between either understanding someone's presentation (or blog) or not.

Till next time


Hard stuff list:
-Metaprogramming
-Blocks
-Lambdas
-eval methods
-bindings
-Singleton
-Method Missing

No comments:

Post a Comment