Have you ever used Jbuilder in a Rails View and found your collection to render slowly? In that case, jsonapi-serializer may be able to improve it easily. For details on how to use jsonapi-serializer, see Official Document. In this article, I will write tips for replacing Jbuilder with jsonapi-serializer. It is a hybrid format that allows Jbuilder and jsonapi-serializer to coexist for easy verification rather than complete replacement. (If you can confirm the effect and need it, you can replace it completely.)
I am writing this article due to some circumstances, and there are the following points to note mainly due to time constraints.
It is a gem that outputs data in JSON API format, and it is set to Speed. Originally developed on Netflix/fast_jsonapi, it has been forked by a volunteer community as it is no longer maintained. Then it became the current jsonapi-serializer/jsonapi-serializer.
Tips
As mentioned earlier, the output of jsonapi-serializer is in the format defined by the JSON API specification, which is difficult to use to replace jbuilder. Therefore, create the following Serializer Module.
module ApplicationSerializer
extend ActiveSupport::Concern
included do
include JSONAPI::Serializer
end
class_methods do
#If you want to write it short, you may want to have the following class method
# def attributes(...)
# new(...).attributes
# end
end
#Extract only the necessary parts
def attributes
data = serializable_hash[:data]
case data
when Hash
data[:attributes]
when Enumerable
data.pluck(:attributes)
else
data
end
end
end
For example, it looks like the following.
ruby:app/views/posts/show.json.jbuilder
json.extract! @post, :id, :title, :content, :published_at
app/serializers/post_serializer.rb
class PostSerializer
include ApplicationSerializer
attributes :id, :title, :content, :published_at
end
ruby:app/views/posts/show.json.jbuilder
json.merge! PostSerializer.new(@post).attributes
ruby:app/views/posts/index.json.jbuilder
json.array! @posts, partial: 'posts/post', as: :post
↓
ruby:app/views/posts/index.json.jbuilder
json.merge! PostSerializer.new(@posts).attributes
(You can pass either single or multiple resources to Serializer)
Recommended Posts