John Lam 1997 — 2026

Fun with const_missing and method_missing

The const_missing and method_missing methods are really important if you want to dynamically extend the Ruby language. They let you dynamically create classes and dynamically add methods to those classes.

Consider this set of unit tests:

class MethodMissingTests < Test::Unit::TestCase
def setup
@obj = System.new
end
def test_method_proxy_caching
assert_equal "joe", @obj.joe
assert_equal "bob", @obj.bob
assert_equal "joe", @obj.joe
assert_equal "kim", @obj.kim
end
end

There’s a lot of magic going on in this code since there isn’t a type called System. When the line of code @obj = System.new runs, it calls Module.const_missing. You can easily override its default implementation:

class Module
def const_missing(name)
const_set(name, Class.new(DynamicProxy))
end
end

To understand why this triggers a const_missing call, you need to realize that a constant such as System is really just an alias for a class object. In my const_missing method, I instantiate a new anonymous class object that derives from another class called DynamicProxy (more on him later), and bind the missing constant symbol to this new, anonymous class object (now it’s not anonymous anymore!).

Let’s look at DynamicProxy:

class DynamicProxy
def method_missing(name)
self.class.class_eval do
define_method(name) { name.to_s }
end
self.method(name).call
end
end

The class object that I created in const_missing will inherit the DynamicProxy method_missing implementation, as will all instances of that class object (in other words all objects created via a System.new call).

If someone attempts to reference a method that doesn’t exist (e.g. System.new.bob), our method_missing method will get called. The interesting piece of magic code is in the self.class.class_eval block. Here, I define the method that was missing with a default implementation that simply returns the name of the missing method as a string. Obviously, I could define whatever I want in the body of the define_method call!

This is the central piece of magic in my Ruby <-> CLR bridge. There are some important details left out of this example for clarity, but this captures the essence of the idea. Most everything else is just plumbing.