A brief overview of how to generate JSON
Today Rails has the following methods for serializing objects in JSON:
- Call to_json () directly.
- Rable
- Active model serializers
- Jbuilder
The first method is ideal for situations where you do not need to serialize nested objects.
@posts.to_json(:include => [...], :methods => [...])
However, forming a JSON response with a list of models, it becomes necessary to serialize the associated models in the desired form.
JbuilderFrom personal experience, the most organically fit into a Rails development is, included by default in Rails 4, JBuilder.
json.extract! message, :id, :content, :chat_id json.user do json.cache!(["user_", message.user_id]) do json.partial! 'users/user', user: message.user end end
RableRABL, compared to other gems, seems to be an ancient monster because of its syntax and slow to do so.
collection :@messages attributes :id, :content, :chat_id child(:user) { attributes :name } node(:read) { |message| message.read_by?(@user) }
ActiveModel :: SerializerActive model serializers proposes to describe JSON in the form of ruby classes, without invented syntax, which reduces the zoo's use of different DSL in the project.
')
Solving performance problems
Small comparison
Test data: 1000 typical messages with the sender and additional fields.
Json:
{ id: 1, content: "Lorem", chat_id: 1, created_at: "2014-06-18T21:47:49.363Z", kind: 0, formatted_content: "<span>Lorem</span>", user: { id: 1, name: "Ivan Petrov", image: "https://lh6.googleusercontent.com/photo.jpg" }, files: [ ], links: [ ] }
to_json: 0.2ms
JBuilder: 129.0ms
JBuilder with OJ: 88.0ms
The numbers are averaged, but the overall picture is clear. It makes no sense to compare different gems among themselves, since the difference is not significant, but objectively, JBuilder is the fastest today.
For convenience you have to pay speed. All the described gems in speed lose the to_json () method several times.
Using JBuilder without configuration will cost you ~ 600.0ms
There are several ways to speed up JBuilder:
- Connect gems: oj, oj_mimic_json, multi_json.
Add MultiJson.use(:oj)
to initialization MultiJson.use(:oj)
What will replace the standard serializer with a faster Oj. - Do not use partials that significantly slow down JBuilder. It has long been created issues in which, despite the closed status, this problem has not actually been resolved.
- Cache templates using the cache built-in JBuilder method!
In the
Staply project (almost open beta) we used JBuilder only at the initial stage of development, gradually switching to the formation of JSON manually using to_json (). What is the olnichno demonstration of the entire concept of Rails, providing a fairly quick and easy development at the beginning with optimization at the end.