Snapshot của rails/jbuilder: 4.4k★ · Ruby. Jbuilder: generate JSON objects with a Builder-style DSL
Tóm tắt dựng từ metadata GitHub của chính dự án — chưa có bài review TopGit. Trang sẽ tự động cập nhật khi bài review đầy đủ được xuất bản.
VÌ SAO CHƯA CÓ REVIEW
TopGit viết bài đầy đủ cho repo có nhiều sao nhất và được yêu cầu nhiều nhất. Trang này là snapshot trong thời gian chờ — xem README gốc ở tab READ ME.
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. Here's a simple
example:
# app/views/messages/show.json.jbuilder
json.content format_content(@message.content)
json.(@message, :created_at, :updated_at)
json.author do
json.name @message.creator.name.familiar
json.email_address @message.creator.email_address_with_name
json.url url_for(@message.creator, format: :json)
end
if current_user.admin?
json.visitors calculate_visitors(@message)
end
json.comments @message.comments, :content, :created_at
json.attachments @message.attachments do |attachment|
json.filename attachment.filename
json.url url_for(attachment)
end
You don't always have or need a collection when building an array.
json.people do
json.child! do
json.id 1
json.name 'David'
end
json.child! do
json.id 2
json.name 'Jamie'
end
end
# => { "people": [ { "id": 1, "name": "David" }, { "id": 2, "name": "Jamie" } ] }
Nested Jbuilder Objects
Jbuilder objects can be directly nested inside each other. Useful for composing objects.
class Person
# ... Class Definition ... #
def to_builder
Jbuilder.new do |person|
person.(self, :name, :age)
end
end
end
class Company
# ... Class Definition ... #
def to_builder
Jbuilder.new do |company|
company.name name
company.president president.to_builder
end
end
end
company = Company.new('Doodle Corp', Person.new('John Stobs', 58))
company.to_builder.target!
# => {"name":"Doodle Corp","president":{"name":"John Stobs","age":58}}
Rails Integration
You can either use Jbuilder stand-alone or directly as an ActionView template
language. When required in Rails, you can create views à la show.json.jbuilder
(the json is already yielded):
# Any helpers available to views are available to the builder
json.content format_content(@message.content)
json.(@message, :created_at, :updated_at)
json.author do
json.name @message.creator.name.familiar
json.email_address @message.creator.email_address_with_name
json.url url_for(@message.creator, format: :json)
end
if current_user.admin?
json.visitors calculate_visitors(@message)
end
Partials
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.
You can also render to a collection of partials inline under a key.
json.comments @post.comments, partial: 'comments/comment', as: :comment
# => { "comments": [{ "content": "Hello everyone!" }, { "content": "To you my good sir!" }] }
You can also provide other locals to the partial you're rendering to.
# Provide the `include_body` local to the partial when rendering a single object
json.post @post, partial: 'posts/post', as: :post, include_body: true
# Provide a local to the partial when rendering a collection.
# Each item in the collection will render with `include_author: true`.
json.comments @post.comments, partial: 'comments/comment', as: :comment, include_author: true
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:
# Use the default `views/comments/_comment.json.jbuilder`, putting @comment as the comment local variable.
# Note, `comment` attributes are "inlined".
json.partial! @comment, as: :comment
is quite different from:
# comment attributes are nested under a "comment" property
json.comment do
json.partial! "/comments/comment.json.jbuilder", comment: @comment
end
You can pass any objects into partial templates with or without :locals option.
json.partial! 'sub_template', locals: { user: user }
# or
json.partial! 'sub_template', user: user
Null Values
You can explicitly make Jbuilder object return null if you want:
json.extract! @post, :id, :title, :content, :published_at
json.author do
if @post.anonymous?
json.null! # or json.nil!
else
json.first_name @post.author_first_name
json.last_name @post.author_last_name
end
end
To prevent Jbuilder from including null values in the output, you can use the ignore_nil! method:
Fragment caching is supported, it uses Rails.cache and works like caching in
HTML templates:
json.cache! ['v1', @person], expires_in: 10.minutes do
json.extract! @person, :name, :age
end
You can also conditionally cache a block by using cache_if! like this:
json.cache_if! !admin?, ['v1', @person], expires_in: 10.minutes do
json.extract! @person, :name, :age
end
Aside from that, the :cached options on collection rendering is available on Rails >= 6.0. This will cache the
rendered results effectively using the multi fetch feature.
If your collection cache depends on multiple sources (try to avoid this to keep things simple), you can name all these dependencies as part of a block that returns an array:
You can set this globally with the class method key_format (from inside your
environment.rb for example):
Jbuilder.key_format camelize: :lower
By default, key format is not applied to keys of hashes that are
passed to methods like set!, array! or merge!. You can opt into
deeply transforming these as well:
You can set this globally with the class method deep_format_keys (from inside your
environment.rb for example):
Jbuilder.deep_format_keys true
Testing JBuilder Response body with RSpec
To test the response body of your controller spec, enable render_views in your RSpec context. This configuration renders the views in a controller test.
Contributing to Jbuilder
Jbuilder is the work of many contributors. You're encouraged to submit pull requests, propose
features and discuss issues.
Trang TopGit này là một snapshot — tab "Readme" hiển thị nguyên văn README của repo (đã bỏ link, giữ ảnh). Repo GitHub ở github.com/rails/jbuilder là nguồn chính thức.
rails/jbuilder có bao nhiêu sao?
rails/jbuilder có 4.4k sao GitHub — tải lại trang để xem số mới nhất, hoặc xem trực tiếp github.com/rails/jbuilder. TopGit phản chiếu số sao của GitHub nhưng không cam kết đến từng phút.
rails/jbuilder có tag gì không?
Bản đồng bộ chưa ghi nhận topic GitHub nào cho rails/jbuilder. GitHub topics hiển thị ở thanh bên phải trang repo — đó là nơi đáng kiểm tra nhất.
rails/jbuilder có website riêng không?
TopGit chưa ghi nhận URL trang chủ cho rails/jbuilder. Phần README ở tab phía trên thường có link demo, hoặc xem mô tả GitHub của repo.
rails/jbuilder còn đang phát triển không?
Commit gần nhất trên rails/jbuilder là 5 tháng trước (theo timestamp GitHub). Repo có 456 fork — một chỉ báo về mức độ quan tâm của cộng đồng.
rails/jbuilder dùng license gì?
rails/jbuilder phát hành theo license MIT. Nên mở file LICENSE trên GitHub để xác nhận — license metadata đôi khi lệch với thực tế dự án.
rails/jbuilder viết bằng ngôn ngữ gì?
rails/jbuilder chủ yếu viết bằng Ruby. Trường "language" của GitHub dựa trên phần lớn byte ở nhánh mặc định.
Đọc đầy đủ README ở tab phía trên.
Vẫn đang phân vân về jbuilder?
Một cú bấm sẽ gửi câu hỏi kèm trang này cho AI — xem AI nói gì về jbuilder.