README.md in jb-0.4.0 vs README.md in jb-0.4.1
- old
+ new
@@ -50,18 +50,22 @@
if current_user.admin?
json[:visitors] = calculate_visitors(@message)
end
-json[:comments] = {
- content: @message.comments.content,
- created_at: @message.comments.created_at
-}
+json[:comments] = @message.comments.map do |comment|
+ {
+ content: comment.content,
+ created_at: comment.created_at
+ }
+end
json[:attachments] = @message.attachments.map do |attachment|
- filename: attachment.filename,
- url: url_for(attachment)
+ {
+ filename: attachment.filename,
+ url: url_for(attachment)
+ }
end
json
```
@@ -108,14 +112,16 @@
``` ruby
# @comments = @post.comments
@comments.reject {|c| c.marked_as_spam_by?(current_user) }.map do |comment|
- body: comment.body,
- author: {
- first_name: comment.author.first_name,
- last_name: comment.author.last_name
+ {
+ body: comment.body,
+ author: {
+ first_name: comment.author.first_name,
+ last_name: comment.author.last_name
+ }
}
end
# => [{"body": "🍣 is omakase...", "author": {"first_name": "Yukihiro", "last_name": "Matz"}}]
```
@@ -220,10 +226,10 @@
inside which [`_render_partial` is called per each element of the given collection](https://github.com/rails/jbuilder/blob/83a682aeebde96c6ef02ce742c0b97dc393f5e22/lib/jbuilder/jbuilder_template.rb#L93),
and then it [falls back to the `view_context`'s `render` method](https://github.com/rails/jbuilder/blob/83a682aeebde96c6ef02ce742c0b97dc393f5e22/lib/jbuilder/jbuilder_template.rb#L100-L103).
So, for example if the collection has 100 elements, Jbuilder's `render partial:` performs `render` method 100 times, and so it calls `find_template` method (which is known as one of the heaviest parts of Action View) 100 times.
-OTOH, Jb simply calls [ActionView::PartialRenderer's `render`](https://github.com/rails/rails/blob/49a881e0db1ef64fcbae2b7ddccfd5ccea26ae01/actionview/lib/action_view/renderer/partial_renderer.rb#L423-L443) which is cleverly implmented to `find_template` only once beforehand, then pass each element to that template.
+OTOH, Jb simply calls [ActionView::PartialRenderer's `render`](https://github.com/rails/rails/blob/49a881e0db1ef64fcbae2b7ddccfd5ccea26ae01/actionview/lib/action_view/renderer/partial_renderer.rb#L423-L443) which is cleverly implemented to `find_template` only once beforehand, then pass each element to that template.
## Benchmarks
Here're the results of a benchmark (which you can find [here](https://github.com/amatsuda/jb/blob/master/test/dummy_app/app/controllers/benchmarks_controller.rb) in this repo) rendering a collection to JSON.