5
3

【Rails】Active Model Serializersとjson-api-serializerの比較

Posted at

はじめに

RailsでAPIモードを扱う時に、Active Model Serializersもしくはjson-api-serializerシリアライザーの選択肢として用いる事がほとんどかと思います。
今回はこれらのシリアライザーについて簡単に比較してみました。

シリアライズとは

オブジェクトデータ構造を、ファイルデータベースネットワーク越しの通信でやり取りできる形式(たいていの場合は文字列)に変換することです。JSONXMLが挙げられます。

比較

特徴 ActiveModel::Serializer json-api-serializer
設計 MVCに沿った構造で、JSON構造を細かくコントロールできる パフォーマンスに特化しており、シンプルな定義で高速にシリアライズ可能
使用例 render json: user, serializer: UserSerializer render json: UserSerializer.new(user).serialized_json
開発元 ライブラリとしての歴史が長く、広範囲にわたるRailsコミュニティによってサポートされている アクティブなメンテナンスとFast-jsonapiの後継Gemの立ち位置で、AMSより速度が圧倒的に速い
コードの簡潔さ 各モデルごとに詳細なシリアライザーを書くことが多いため、コード量が増えることがある シリアライザーの定義がシンプルで、コード量を抑えることができる
GitHub スター数 約5.3k 約1.3k

ActiveModel::Serializer

gem 'active_model_serializers'
class UsersController < ApplicationController
  def show
    user = User.find(params[:id])
    render json: user, serializer: UserSerializer
  end
end
使用例
class UserSerializer < ActiveModel::Serializer
  attributes :id, :name, :email
  has_many :posts
  has_one :profile
  
  def posts
    object.posts.limit(10)
  end
end

ActiveModel::Serializerの場合はシリアライザー内にメソッドを定義できる為、容易にカスタマイズが可能です。
一方で、ビジネスロジックが肥大化してしまうと、モデルファイルとの区分けや見通しが悪くなる為、設計を考える必要があります。

json-api-serializer

gem 'jsonapi-serializer'
class UsersController < ApplicationController
  def show
    user = User.find(params[:id])
    render json: UserSerializer.new(user).serializable_hash.to_json
  end
end
使用例
class UserSerializer
  include JSONAPI::Serializer
  attributes :id, :name, :email
  has_many :posts, serializer: PostSerializer
  has_one :profile, serializer: ProfileSerializer
end

json-api-serializerNETFLIXが開発したfast_jsonapiを基に作られたGemです。

fast_jsonapiパフォーマンステストによると、Active Model Serializersと比較して最大40倍以上高速に動作したことが結果として得られたそうです。

一方でfast_jsonapiのメンテナンスは止まっており、現状唯一シリアライザーとしてメンテナンスされているjson-api-serializerを扱う事がスタンダードかもしれません。

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3