It can be hard to understand concepts like ‘meta-programming’ without seeing a real world example first. In this post, we’ll do exactly that.
Jbuilder utilizes Ruby’s meta-programming ideas to create any json structure imaginable. It’s amazing once you discover how it actually works. And how it achieves that with a beautiful builder-style DSL (Domain Specific Language). Let’s jump in.
Let’s create a basic JSON structure with Jbuilder in order to understand how it works:
Which will produce the following json:
"age" : "31"
But what’s really interesting is that
json doesn’t have a
age method. So how come it doesn’t raise a
NoMethodError when we call it?
Well the reason is because of Ruby’s
method_missing meta-programming hook. What it does is take any missing hit — a call to a method that doesn’t exist — and do something with it at run-time. In the case of Jbuilder
method_missing looks something like this:
method_messing just calls
set! while passing its arguments. Then
set! ultimately saves the key in the
attributes hash which Jbuilder then uses to produce the actual json:
def set!(key, value)
@attributes[_key(key)] = value
That’s it! Jbuilder essentially creates any json hash you wish while using
method_missing and producing the key at run-time.
Thanks for reading!