[Ruby on Rails (RoR)] Use rails jbuilder to generate JSON objects with a Builder-style DSL
jbuilder
Jbuilder gives you a simple DSL for declaring JSON structures that beats manipulating giant hash structures. This is particularly helpful when the generation process is fraught with conditionals and loops. JSON objects can be use in RESTful API or composing objects.
Example
Here’s a simple example:
1 | # app/views/messages/show.json.jbuilder |
This will build the following structure:
1 | { |
Dynamical Attribute
To define attribute and structure names dynamically, use the set! method:
1 | json.set! :author do |
Attribute Merge
To merge existing hash or array to current context:
1 | hash = { author: { name: "David" } } |
Array
Top level arrays can be handled directly. Useful for index and other collection actions.
1 | # @comments = @post.comments |
You can also extract attributes from array directly.
1 | # @people = People.all |
Jbuilder Object
Jbuilder objects can be directly nested inside each other. Useful for composing objects.
1 | # app/jbuilder/person_jbuilder.rb |
You can either use Jbuilder stand-alone or directly as an ActionView template language. When required in Rails, you can create views a la show.json.jbuilder (the json is already yielded):
1 | # Any helpers available to views are available to the builder |
Partial Render
You can use partials as well. The following will render the file views/comments/_comments.json.jbuilder, and set a local variable comments with all this message’s comments, which you can use inside the partial.
1 | json.partial! 'comments/comments', comments: @message.comments |
It’s also possible to render collections of partials:
1 | json.array! @posts, partial: 'posts/post', as: :post |
The as: :some_symbol is used with partials. It will take care of mapping the passed in object to a variable for the partial. If the value is a collection (either implicitly or explicitly by using the collection: option, then each value of the collection is passed to the partial as the variable some_symbol. If the value is a singular object, then the object is passed to the partial as the variable some_symbol.
Be sure not to confuse the as: option to mean nesting of the partial. For example:
1 | # Use the default `views/comments/_comment.json.jbuilder`, putting @comment as the comment local variable. |
You can pass any objects into partial templates with or without :locals option.
1 | json.partial! 'sub_template', locals: { user: user } |
You can explicitly make Jbuilder object return null if you want:
1 | json.extract! @post, :id, :title, :content, :published_at |
To prevent Jbuilder from including null values in the output, you can use the ignore_nil! method:
1 | json.ignore_nil! |
Fragment caching
Fragment caching is supported within rails/jbuilder: Jbuilder: generate JSON objects with a Builder-style DSL - https://github.com/rails/jbuilder, it uses Rails.cache and works like caching in HTML templates:
1 | json.cache! ['v1', @person], expires_in: 10.minutes do |
You can also conditionally cache a block by using cache_if! like this:
1 | json.cache_if! !admin?, ['v1', @person], expires_in: 10.minutes do |
If you are rendering fragments for a collection of objects, have a look at yonahforst/jbuilder_cache_multi - https://github.com/yonahforst/jbuilder_cache_multi gem. It uses fetch_multi (>= Rails 4.1) to fetch multiple keys at once.
Renders the given block for each item in the collection. Accepts optional ‘key’ attribute in options (e.g. key: ‘v1’).
Note: At the moment, does not accept the partial name as an argument (#todo)
Examples:
1 | json.cache_collection! @people, expires_in: 10.minutes do |person| |
Last thing: If you are using a collection for the cache key, may I recommend the ‘scope_cache_key’ gem? (check out my fork for a Rails 4 version: https://github.com/joshblour/scope_cache_key). It very quickly calculates a hash for all items in the collection (MD5 hash of updated_at + IDs).
You can also conditionally cache a block by using cache_collection_if! like this:
1 | json.cache_collection_if! do_cache?, @people, expires_in: 10.minutes do |person| |
Key Format
Keys can be auto formatted using key_format!. Specifies formatting to be applied to the key. Passing in a name of a function will cause that function to be called on the key. So :upcase will upper case the key. You can also pass in lambdas for more complex transformations.
Example:
1 | json.key_format! :upcase |
You can pass parameters to the method using a hash pair.
1 | json.key_format! camelize: :lower |
Lambdas can also be used.
1 | json.key_format! ->(key){ "_" + key } |
You can set this globally with the class method key_format (from inside your config/initializers/jbuilder.rb or environment.rb for example):
1 | # config/initializers/jbuilder.rb |
See lib/jbuilder.rb to learn more usages.
FAQS
return within block will cause json can not render content within block
1 | return if data.blank? |
References
[3] yonahforst/jbuilder_cache_multi - https://github.com/yonahforst/jbuilder_cache_multi