API development: Jbuilder
Jbuilder builds JSON responses in Rails through ordinary method calls on an object named json. The lessons read the .json.jbuilder views of one app line by line, along with the installed jbuilder 2.15.1 source. They cover the implicit setter that routes calls through method_missing to set!, json.array! for collections, and json.partial! for shared shapes. They also explain how Rails registers the jbuilder handler and picks a template for a JSON request. Last, they compare shaped views with calling to_json or as_json on a model.
What you'll learn
- ✓How implicit calls like json.status reach set! through method_missing
- ✓Building nested objects and arrays under a key with set! and a block
- ✓Turning a mixed collection into a JSON array with json.array!
- ✓What json.partial! does and when a shared JSON shape calls for it
- ✓How Rails registers the jbuilder handler and finds a .json.jbuilder file for a request
- ✓Why shaping JSON in a view differs from calling to_json or as_json on a model
Six .json.jbuilder views, already shipping in this app
On a development database, that returns:
Read the full lesson free →Curriculum
7 lessonsSix .json.jbuilder views, already shipping in this app
Compares a model dumped with to_json against a four-key search result and introduces the json object.
json.key value is set!, in the sandbox view
Shows how implicit calls such as json.status reach set! through method_missing in the sandbox execute view.
json.array!: turning a mixed collection into a JSON array
Reads the search view, where json.array! turns a mixed list of courses and lessons into a JSON array.
json.partial!: installed, not needed by this app yet
Explains what json.partial! does and why none of the app's six Jbuilder views uses it yet.
How Rails finds a .json.jbuilder file
Covers the railtie's handler registration, the Accept header and how Rails resolves a request to a .json.jbuilder file.
Shaping vs. dumping: Jbuilder against this app's to_json and as_json
Contrasts to_json on a model, which dumps all 14 columns, with the four chosen keys from Jbuilder.
Putting it together: shaping JSON on purpose, one call at a time
Reviews set!, array!, partial!, template lookup and shaping versus dumping, ending with a small pure Ruby challenge.