Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Markup it is

  • Loading branch information...
commit c9690b4a7494ee8624bdf7b5ae88b2c8a52f9a9d 1 parent d050bb7
David Heinemeier Hansson dhh authored

Showing 1 changed file with 58 additions and 0 deletions. Show diff stats Hide diff stats

  1. +58 0 README.md
58 README.md
Source Rendered
... ... @@ -0,0 +1,58 @@
  1 +Json Builder
  2 +============
  3 +
  4 +Json builder 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. Here's a simple example:
  5 +
  6 +JsonBuilder.encode do |json|
  7 + json.content format_content(@message.content)
  8 + json.extract! @message, :created_at, :updated_at
  9 +
  10 + json.author do |json|
  11 + json.name @message.creator.name.familiar
  12 + json.email_address @message.creator.email_address_with_name
  13 + end
  14 +
  15 + if current_user.admin?
  16 + json.visitors calculate_visitors(@message)
  17 + end
  18 +
  19 + json.comments @message.comments, :content, :created_at
  20 +end
  21 +
  22 +This will build the following structure:
  23 +
  24 + {
  25 + "content": "<p>This is <i>serious</i> monkey business",
  26 + "created_at": "2011-10-29T20:45:28-05:00",
  27 + "updated_at": "2011-10-29T20:45:28-05:00",
  28 +
  29 + "author": {
  30 + "name": "David H.",
  31 + "email_address": "'David Heinemeier Hansson' <david@heinemeierhansson.com>"
  32 + },
  33 +
  34 + "visitors": 15,
  35 +
  36 + "comments": [
  37 + { "content": "Hello everyone!", "created_at": "2011-10-29T20:45:28-05:00" },
  38 + { "content": "To you my good sir!", "created_at": "2011-10-29T20:47:28-05:00" }
  39 + ]
  40 + }
  41 +
  42 +You can either use JsonBuilder stand-alone or directly as an ActionView template language. When required in Rails, you can create views ala show.json.jbuilder (the json is already yielded):
  43 +
  44 +# Any helpers available to views are available to the builder
  45 +json.content format_content(@message.content)
  46 +json.extract! @message, :created_at, :updated_at
  47 +
  48 +json.author do |json|
  49 + json.name @message.creator.name.familiar
  50 + json.email_address @message.creator.email_address_with_name
  51 +end
  52 +
  53 +if current_user.admin?
  54 + json.visitors calculate_visitors(@message)
  55 +end
  56 +
  57 +# You can use partials as well, just remember to pass in the json instance
  58 +render @message.comments, json: json

0 comments on commit c9690b4

Please sign in to comment.
Something went wrong with that request. Please try again.