Today I put together a little magic on the Ruby Hash that lets me write really nice DSL extensions. Calling it MethodicHash, I extended the lookup of a value using a key, and added a method_missing to do a lookup with the name of the missing method as a key:
class MethodicHash < Hash
def [](key)
begin
super(key) || super(key.to_s) || super(key.to_sym)
rescue
nil
end
end
def method_missing(method,*args)
self[method]
end
end
It might not look like much, but when you've embedded a DSL into your code with a require and you've backed it with a MethodicHash, you can say things like foo.bar
instead of foo['bar']
or foo[:bar]
making the code ever so much more readable. Hiding coding details like this so simply and easily is one of Ruby's greatest benefits to the programmer.The MethodicHash is a jumping-off point to more complex dynamics that I'll be hiding under the surface. More will definitely be coming.
No comments:
Post a Comment