JSON in Rails behind the scenes

Liroy Leshed
· 1 min read

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:

json.name 'liroy'
json.age '31'

Which will produce the following json:

{
"name": "liroy",
"age" : "31"
}

But what’s really interesting is that json doesn’t have a name or 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:

def method_missing(*args)
set!(*args)
end

The 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
end

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!

Ruby Inside

Ruby articles and posts

Liroy Leshed

Written by

Founder & CEO @ http://squeezerhq.com

Ruby Inside

Ruby articles and posts

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade