Dynamic Creation of Instance Methods In Ruby with define method and method missing

February 28th, 2011

Dynamic Creation of Instance Methods In Ruby with define_method and method_missing

This is really, really cool. What does it do? If you are familiar with define_method, you know that it can dynamically define class methods. That is very cool!

And if you are familiar with method_missing, you know that it can act as a "catch-all" for non-existent instance methods. Cool, huh?!?

I only recently came to realize that the two can be used together, so define instance methods - first by catching non-existent method calls, then by defining the method, so that future calls to the same method would be optimized. Seriously, how cool is that!?

This is actually how ActiveRecord manages the slew of Model access helpers it provides access to via methods like find_one_by_name('myname').

Yearly Indexes: 2003 2004 2006 2007 2008 2009 2010 2011 2012 2013 2015 2019 2020 2022