Last Updated: February 25, 2016
· taybenlor

JSON Views with JBuilder

Often when it calls to render JSON to the browser it's a bit too easy to do

respond_with(@posts = current_user.posts)

and leave it at that. Soon you'll override as_json and eventually, given a complex enough application, you'll have presentation logic in the model and the controller.


Fortunately this problem is solved with JBuilder.

From the README:
Jbuilder gives you a simple DSL for declaring JSON structures that beats massaging giant hash structures. This is particularly helpful when the generation process is fraught with conditionals and loops.

I won't paste the full example from the README, but a quick preview:

json.content format_content(@message.content)
json.(@message, :created_at, :updated_at) do |json|
  json.email_address @message.creator.email_address_with_name
  json.url url_for(@message.creator, format: :json)

if current_user.admin?
  json.visitors calculate_visitors(@message)

About 6 months ago I switched one of our larger applications over to JBuilder and so far it's been a dream. Having JSON view partials is incredibly powerful and this has allowed for a lot of code sharing between different parts of our API. It also means I've been able to remove a lot of ugly hash manipulation code from models and controllers.

If you're working with JSON I strongly recommend you make the switch to JBuilder. Especially on new projects.

If you're currently doing something similar with ERB or another system, I recommend a look at JBuilder. The Builder-like DSL is very nice and integrates super nicely with presentation logic.

Say Thanks

1 Response
Add your response


are you still using respond_with now that you've implementing jbuilder views?

over 1 year ago ·