fast_jsonapi 使用指南:用 Ruby 快速构建 JSON:API 序列化器

原创2026-10-14 13:10:521,620 阅读
文章标签:后端

fast_jsonapi 使用指南:用 Ruby 快速构建 JSON:API 序列化器

导读

本文以 README.md 为主体,系统讲解 fast_jsonapi 这款 JSON:API(jsonapi.org 规范)Ruby 序列化库的完整用法:从 Gem 安装、Rails 生成器、序列化器定义,到对象/集合序列化、复合文档(included)、缓存、Params、条件属性/关系、稀疏字段集(Sparse Fieldsets)、自定义选项与 Skylight 插桩等全部能力,并结合仓库源码(object_serializer.rb、serialization_core.rb 等)剖析底层实现原理。读完本文,你将能够独立为任何 Ruby 对象(普通 Ruby 类、ActiveRecord 模型、Struct 等)定义高性能序列化器,并产出符合 JSON:API 规范的响应。

维护状态提醒:本项目已停止维护(README 顶部明确标注 "This project is no longer maintained")。README 官方建议:如需继续使用,可考虑社区 fork 项目 jsonapi-serializer/jsonapi-serializer。本文所有内容均以当前仓库(版本号为 1.5,见 version.rb)的实际代码与文档为准。

一、项目定位与设计目标

fast_jsonapi 是一个面向 Ruby Objects 的 JSON:API 序列化器,其声明式语法与 Active Model Serializer(AMS)相似,但设计目标截然不同——它追求"闪电般的速度"(README 原文 "A lightning fast JSON:API serializer"),并通过内置的 RSpec 性能测试将这一目标固化为持续约束:

  • 仓库在 object_serializer_performance_spec.rb 中内置了与 AMS 的对比基准,要求 fast_jsonapi 生成 Ruby Hash 的速度至少是 AMS 的 25 倍(测试中通过 speed_factor: 25 与 expect(hash_speed_up).to be >= SERIALIZERS[:ams][:speed_factor] 断言强制保证)。
  • 性能测试还对绝对耗时设限:1000 条记录的 serializable_hash 需在 50 ms 内完成、serialized_json 需在 60 ms 内完成、带 include 和 meta 的 1000 条记录序列化需在 75 ms 内完成(见 object_serializer_performance_spec.rb)。
  • README 给出了 250 条记录的实际基准示例输出:
$ rspec
Active Model Serializer serialized 250 records in 138.71 ms
Fast JSON API serialized 250 records in 3.01 ms

需要说明的是,上述数字来自 README 与性能规格中的示例,实际结果取决于运行环境、模型复杂度与数据规模;更详细的测试口径可参阅仓库内的 performance_methodology.md。

核心特性(README 官方列表)

  • 与 Active Model Serializer 相似的声明式语法;
  • 支持 belongs_to、has_many、has_one 三种关系;
  • 支持复合文档(included);
  • 对复合文档的序列化做了优化;
  • 内置缓存(Caching)。

二、安装

在应用的 Gemfile 中加入:

gem 'fast_jsonapi'

然后执行:

$ bundle install

依赖与环境适配

从 fast_jsonapi.gemspec 可以看到:

  • 要求 Ruby >= 2.0.0;
  • 运行时依赖 activesupport >= 4.2;
  • 开发依赖包括 activerecord >= 4.2、rspec ~> 3.5.0、oj ~> 3.3、skylight ~> 1.3 等。

在加载层面,lib/fast_jsonapi.rb 会根据宿主环境做差异化处理:

module FastJsonapi
  require 'fast_jsonapi/object_serializer'
  if defined?(::Rails)
    require 'fast_jsonapi/railtie'
  elsif defined?(::ActiveRecord)
    require 'extensions/has_one'
  end
end

即在 Rails 环境中加载 railtie.rb,在纯 ActiveRecord(非 Rails)环境中直接加载 has_one.rb 扩展;这保证了库既能与 Rails 深度集成,也能独立于 Rails 用于任意 Ruby 对象。

三、快速上手:Rails Generator 生成序列化器

如果在 Rails 项目中使用,可以直接使用内置生成器(实现见 serializer_generator.rb,模板见 serializer.rb.tt):

rails g serializer Movie name year

该命令会在 app/serializers/movie_serializer.rb 生成如下内容的序列化器:

class MovieSerializer
  include FastJsonapi::ObjectSerializer
  attributes :name, :year
end

生成器支持命名空间(class_path)与任意数量的属性参数,非常适合快速搭建 API 骨架。

四、序列化器定义与模型约定

4.1 模型定义

序列化器可以从任意 Ruby 对象读取数据,仓库测试中以普通 Ruby 类(见 movie_context.rb 中的 Movie 类)和 Struct(MovieStruct)两种形态验证了这一通用性。README 中的示例模型:

class Movie
  attr_accessor :id, :name, :year, :actor_ids, :owner_id, :movie_type_id
end

4.2 序列化器定义

class MovieSerializer
  include FastJsonapi::ObjectSerializer
  set_type :movie  # optional
  set_id :owner_id # optional
  attributes :name, :year
  has_many :actors
  belongs_to :owner, record_type: :user
  belongs_to :movie_type
end

关键点:

  • include FastJsonapi::ObjectSerializer 引入了 object_serializer.rb 中定义的模块能力(该模块内部 include SerializationCore,最终能力来自 serialization_core.rb);
  • set_type 是可选的:从 object_serializer.rb 可以看到,序列化器类被 include 时会自动执行 set_type(reflected_record_type)——即把类名末尾的 Serializer 去掉、underscore 化后作为默认 type(如 MovieSerializer → :movie);
  • set_id 是可选的:默认从记录的 id 方法取值,如果对象没有 id 方法,serialization_core.rb 中的 id_from_record 会抛出 MandatoryField 异常("id is a mandatory field in the jsonapi spec");
  • has_many :actors 默认通过读取 actor_ids 获取 ID 列表、读取 actors 方法获取关联对象(ID 方法名的推导逻辑见 object_serializer.rb 的 create_relationship);
  • belongs_to :owner, record_type: :user 通过 record_type 覆盖关联对象的 JSON:API 类型。

4.3 示例对象

movie = Movie.new
movie.id = 232
movie.name = 'test movie'
movie.actor_ids = [1, 2, 3]
movie.owner_id = 3
movie.movie_type_id = 1
movie

五、对象序列化:Hash 与 JSON 两种出口

5.1 两个核心方法

# 返回 Ruby Hash(JSON:API 文档结构)
hash = MovieSerializer.new(movie).serializable_hash

# 返回 JSON 字符串
json_string = MovieSerializer.new(movie).serialized_json

其中:

  • serializable_hash 也以别名 to_hash 提供(见 object_serializer.rb);
  • serialized_json 内部通过 ActiveSupport::JSON.encode(serializable_hash) 实现(见 object_serializer.rb);
  • 另外,serialization_core.rb 中还覆盖了类级 to_json(payload) 方法,它会委托给 multi_to_json.rb 中的 FastJsonapi::MultiToJson.to_json——后者会按可用性依次尝试 OJ、Yajl、JrJackson、JSON、Gson、ActiveSupport 等编码器,优先使用最快的 JSON 引擎来序列化整个 payload。

5.2 序列化输出结构(JSON:API 规范)

{
  "data": {
    "id": "3",
    "type": "movie",
    "attributes": {
      "name": "test movie",
      "year": null
    },
    "relationships": {
      "actors": {
        "data": [
          {
            "id": "1",
            "type": "actor"
          },
          {
            "id": "2",
            "type": "actor"
          }
        ]
      },
      "owner": {
        "data": {
          "id": "3",
          "type": "user"
        }
      }
    }
  }
}

注意示例输出中 id 是 "3" 而非 "232"——这正是 set_id :owner_id 起的作用,且所有 ID 都会通过 id_hash 被规范化为字符串(见 serialization_core.rb)。

六、Key Transforms:键名风格转换

默认情况下 fast_jsonapi 对键名做下划线(underscore)处理,同时支持与 AMS 相同的键转换方式,通过 set_key_transform 指定:

class MovieSerializer
  include FastJsonapi::ObjectSerializer
  # Available options :camel, :camel_lower, :dash, :underscore(default)
  set_key_transform :camel
end

四种转换的对应关系(实现见 object_serializer.rb):

set_key_transform :camel        # "some_key" => "SomeKey"
set_key_transform :camel_lower  # "some_key" => "someKey"
set_key_transform :dash         # "some_key" => "some-key"
set_key_transform :underscore   # "some_key" => "some_key"

实现细节:

  • set_key_transform 底层是把 transform_method 设置为对应的 ActiveSupport 转换方法(:camelize、[:camelize, :lower]、:dasherize、:underscore),并同步对 record_type 重新执行转换;
  • 所有键(属性名、关系名、link 名、record_type)在定义时都经过 run_key_transform(见 object_serializer.rb)统一处理;
  • 旧 API use_hyphen 已废弃,会打印弃用警告并建议改用 set_key_transform :dash(见 object_serializer.rb)。

七、Attributes:属性定义的三类写法

7.1 默认读取同名属性

attributes 方法(同时以单数 attribute 作为别名,见 object_serializer.rb)默认从模型同名属性读取:

class MovieSerializer
  include FastJsonapi::ObjectSerializer

  attribute :name
end

7.2 用块(Block)定义自定义属性

模型中不存在、但需要序列化的属性,可以用 Ruby 块声明:

class MovieSerializer
  include FastJsonapi::ObjectSerializer

  attributes :name, :year

  attribute :name_with_year do |object|
    "#{object.name} (#{object.year})"
  end
end

块语法也可以覆盖对象上的同名属性:

class MovieSerializer
  include FastJsonapi::ObjectSerializer

  attribute :name do |object|
    "#{object.name} Part 2"
  end
end

7.3 用 Proc 快捷方式重命名属性

当需要输出不同的键名、但取值来自对象的某个方法/访问器时,可以使用 &:method 快捷语法:

class MovieSerializer
  include FastJsonapi::ObjectSerializer

  attributes :name

  attribute :released_in_year, &:year
end

底层实现

属性最终被封装为 attribute.rb 中的 Attribute 对象:序列化时若 method 是 Proc,则按 arity(参数个数)决定调用 method.call(record) 还是 method.call(record, serialization_params);否则调用 record.public_send(method)。块/方法/键名在 attributes 类方法中统一构建(见 object_serializer.rb)。

八、Links:每个对象的链接

8.1 对象级链接(Links Per Object)

用 link 方法定义。默认直接读取模型上的同名属性;也可以指定对象上要调用的方法名,或使用块(块内可访问 params):

class MovieSerializer
  include FastJsonapi::ObjectSerializer

  link :public_url

  link :self, :url

  link :custom_url do |object|
    "http://movies.com/#{object.name}-(#{object.year})"
  end

  link :personalized_url do |object, params|
    "http://movies.com/#{object.name}-#{params[:user].reference_code}"
  end
end

链接在 link.rb 的 Link#serialize 中实现:Proc 按 arity 区分单参(record)与双参(record, params),非 Proc 则 record.public_send(method)。多个链接由 links_hash 统一汇聚(见 serialization_core.rb)。

8.2 关系上的链接(Links on a Relationship)

JSON:API 规范允许在关系(relationship)上携带链接,典型场景是:父文档已加载,但由于体积限制稍后再加载关联文档(对应规范的 related resource links)。通过关系的 links: 选项声明:

class MovieSerializer
  include FastJsonapi::ObjectSerializer

  has_many :actors, links: {
    self: :url,
    related: -> (object) {
      "https://movies.com/#{object.id}/actors"
    }
  }
end

这会为关系生成 self 引用,以及用于稍后加载 actors 关系的 related 链接。

注意:设置 links: 并不会自动禁用关系 data 的加载。如果只想输出链接、不输出关系数据,需要配合 lazy_load_data: true:

  has_many :actors, lazy_load_data: true, links: {
    self: :url,
    related: -> (object) {
      "https://movies.com/#{object.id}/actors"
    }
  }

从 relationship.rb 的 serialize 实现可以看到:当 lazy_load_data 为真时,输出哈希中只包含 links,不再填充 data 键。

九、Meta Per Resource:每个资源的元信息

对于集合中的每个资源,可以包含一个 meta 对象,用于承载无法表示为属性或关系的非标准元信息:

class MovieSerializer
  include FastJsonapi::ObjectSerializer

  meta do |movie|
    {
      years_since_release: Date.current.year - movie.year
    }
  end
end

从源码看,meta 类方法把块存为 meta_to_serialize(见 object_serializer.rb),序列化时由 meta_hash 调用(见 serialization_core.rb),在每个 record 的 record_hash 中都会执行。

十、复合文档(Compound Document):顶层与嵌套 included

通过 options[:include] 支持顶层及嵌套的关联序列化:

options = {}
options[:meta] = { total: 2 }
options[:links] = {
  self: '...',
  next: '...',
  prev: '...'
}
options[:include] = [:actors, :'actors.agency', :'actors.agency.state']
MovieSerializer.new([movie, movie], options).serialized_json
  • include 项支持用点号(.)表达嵌套关系,例如 'actors.agency.state' 表示在 actors 下继续展开 agency,再展开 agency 下的 state;
  • include 列表在 object_serializer.rb 的 process_options 中被符号化并校验(validate_includes! 会确保每个 include 项确实声明为关系,否则抛出 ArgumentError,见 object_serializer.rb);
  • 嵌套展开由 serialization_core.rb 的 get_included_records 递归完成:parse_include_item 拆分点号路径、remaining_items 处理剩余嵌套层级,并用 known_included_objects 以 "#{record_type}_#{id}" 为键去重,避免同一关联对象被重复输出;
  • 每个 record 的 included 结果会按 include 项排序后合并(includes_list.sort),保证输出确定性。

十一、集合序列化(Collection Serialization)

将数组传给序列化器即可输出集合文档:

options[:meta] = { total: 2 }
options[:links] = {
  self: '...',
  next: '...',
  prev: '...'
}
hash = MovieSerializer.new([movie, movie], options).serializable_hash
json_string = MovieSerializer.new([movie, movie], options).serialized_json

集合与单对象的入口分流在 serializable_hash 中完成(见 object_serializer.rb):集合走 hash_for_collection,单对象走 hash_for_one_record。

11.1 用 is_collection 精确控制集合判定

可以通过 is_collection 选项对"单对象 vs 集合"获得更精确的控制:

options[:is_collection]

其取值语义:

  • nil 或未提供:使用自动检测逻辑(autodetect)判断输入是单个对象还是集合;
  • true:无论输入是什么,一律按集合处理;
  • false:无论输入是什么,一律按单个对象处理。

自动检测逻辑与大多数数据库工具包(ActiveRecord、Sequel 等)兼容,但 不能 保证单对象与集合总能被正确识别。其具体实现(见 object_serializer.rb)是:

def is_collection?(resource, force_is_collection = nil)
  return force_is_collection unless force_is_collection.nil?

  resource.respond_to?(:size) && !resource.respond_to?(:each_pair)
end

即:只要对象响应 size 且不响应 each_pair(如 Hash),就判定为集合。因此在遇到边界情况(例如同时具备 size 和 each_pair 的 Hash 包装对象、或代理集合等)时,显式传入 is_collection 是最稳妥的做法。

十二、Caching:基于 Rails.cache 的序列化缓存

启用缓存要求模型上定义 cache_key 方法:

class MovieSerializer
  include FastJsonapi::ObjectSerializer
  set_type :movie  # optional
  cache_options enabled: true, cache_length: 12.hours
  attributes :name, :year
end

12.1 cache_options 的三个参数

cache_options 的完整形式(见 object_serializer.rb 与 README 的"Customizable Options"表格):

参数 作用 默认值
enabled 是否启用缓存 false
cache_length 缓存有效期 5.minutes
race_condition_ttl 防缓存击穿的竞态条件 TTL(用于 Rails.cache.fetch 的 race_condition_ttl 参数) 5.seconds

示例:

cache_options enabled: true, cache_length: 12.hours, race_condition_ttl: 10.seconds

12.2 底层机制

在 serialization_core.rb 的 record_hash 中,开启缓存后,记录的 id/attributes/可缓存关系/links 部分通过 Rails.cache.fetch(record.cache_key, expires_in: cache_length, race_condition_ttl: race_condition_ttl) 整块缓存;而不可缓存的关系(未标记 cached: true 的关系)与 meta 部分仍会在每次序列化时实时计算并合并进结果。

同时,关系级别支持单独标记缓存(cached: true),例如:

has_many :actors, cached: true

此时该关系会被归入 cachable_relationships_to_serialize(见 object_serializer.rb 的 add_relationship),随记录主体一起被缓存;反之进入 uncachable_relationships_to_serialize,每次实时计算。

缓存行为在 object_serializer_caching_spec.rb 中有完整验证:测试用 ActiveSupport::Cache::MemoryStore 模拟 Rails.cache,并断言修改 movie.name 后再次序列化仍返回缓存中的旧值("uses cached values for the record")。

注意:缓存机制强依赖 Rails.cache(代码中直接引用 Rails.cache.fetch),因此启用缓存需要在 Rails 环境或自行提供 Rails.cache 的环境下使用。

十三、Params:向序列化器传入上下文参数

某些属性的取值需要比记录本身更多的信息,例如访问权限、或当前登录用户相关信息。options[:params] 正是为此设计:通过它传入一个附加参数 Hash。

在定义自定义属性或关系时,只要在块中声明第二个参数,就自动"接入"了 params:

class MovieSerializer
  include FastJsonapi::ObjectSerializer

  attributes :name, :year
  attribute :can_view_early do |movie, params|
    # in here, params is a hash containing the `:current_user` key
    params[:current_user].is_employee? ? true : false
  end

  belongs_to :primary_agent do |movie, params|
    # in here, params is a hash containing the `:current_user` key
    params[:current_user].is_employee? ? true : false
  end
end

# ...
current_user = User.find(cookies[:current_user_id])
serializer = MovieSerializer.new(movie, {params: {current_user: current_user}})
serializer.serializable_hash

要点:

  • 只接收资源的块(单参数块)依然完全可用;
  • params 在 object_serializer.rb 的 process_options 中处理:@params = options[:params] || {},且必须是 Hash,否则抛出 ArgumentError("params option passed to serializer must be a hash");
  • 属性块按 arity 决定是否接收 params(见 attribute.rb),关系块同理(见 relationship.rb 的 fetch_associated_object)。

十四、条件属性(Conditional Attributes)

通过 attribute 方法的 if 键传入一个 Proc 实现条件序列化:Proc 返回 true 则输出该属性,返回 false 则不输出。Proc 的第一个参数是记录,第二个参数(可选)是传给序列化器的 params:

class MovieSerializer
  include FastJsonapi::ObjectSerializer

  attributes :name, :year
  attribute :release_year, if: Proc.new { |record|
    # Release year will only be serialized if it's greater than 1990
    record.release_year > 1990
  }

  attribute :director, if: Proc.new { |record, params|
    # The director will be serialized only if the :admin key of params is true
    params && params[:admin] == true
  }
end

# ...
current_user = User.find(cookies[:current_user_id])
serializer = MovieSerializer.new(movie, { params: { admin: current_user.admin? }})
serializer.serializable_hash

条件 Proc 被保存在 Attribute 的 conditional_proc 中,include_attribute? 负责判定(见 attribute.rb)。条件属性与 params 的组合用法(MovieOptionalParamsDataSerializer、MovieOptionalRecordDataSerializer)在 movie_context.rb 中有现成示例。

十五、条件关系(Conditional Relationships)

同理,关系也可以通过 if 键条件化输出,Proc 语义与条件属性一致:

class MovieSerializer
  include FastJsonapi::ObjectSerializer

  # Actors will only be serialized if the record has any associated actors
  has_many :actors, if: Proc.new { |record| record.actors.any? }

  # Owner will only be serialized if the :admin key of params is true
  belongs_to :owner, if: Proc.new { |record, params| params && params[:admin] == true }
end

# ...
current_user = User.find(cookies[:current_user_id])
serializer = MovieSerializer.new(movie, { params: { admin: current_user.admin? }})
serializer.serializable_hash

关系侧的条件判定由 relationship.rb 的 include_relationship? 完成;条件关系也会影响复合文档展开——get_included_records 中会先调用 include_relationship? 决定是否继续 include(见 serialization_core.rb)。

十六、稀疏字段集(Sparse Fieldsets)

通过 fields 选项,可以按 record type 选择性返回属性与关系:

class MovieSerializer
  include FastJsonapi::ObjectSerializer

  attributes :name, :year
end

serializer = MovieSerializer.new(movie, { fields: { movie: [:name] } })
serializer.serializable_hash

实现机制(见 serialization_core.rb):

  • process_options 中的 deep_symbolize 会把 fields 的键与值全部符号化(见 object_serializer.rb);
  • 序列化时 attributes_hash 与 relationships_hash 通过 attributes.slice(*fieldset) 只保留 fieldset 中列出的键;
  • 每个 record type 对应各自的 fieldset 键(本例为 :movie),include 进来的其他类型记录使用各自类型的 fieldset(见 get_included_records 中 fieldsets[serializer.record_type])。

十七、使用 Helper 方法复用逻辑

可以把其他 Ruby 模块的代码 mix-in 进序列化器以复用函数。由于序列化器是在 class 的上下文中求值(而非类的实例),被 mix-in 的方法必须表现为类方法。

17.1 使用 ActiveSupport::Concern

module AvatarHelper
  extend ActiveSupport::Concern

  class_methods do
    def avatar_url(user)
      user.image.url
    end
  end
end

class UserSerializer
  include FastJsonapi::ObjectSerializer

  include AvatarHelper # mixes in your helper method as class method

  set_type :user

  attributes :name, :email

  attribute :avatar do |user|
    avatar_url(user)
  end
end

17.2 使用纯 Ruby(Plain Old Ruby)

module AvatarHelper
  def avatar_url(user)
    user.image.url
  end
end

class UserSerializer
  include FastJsonapi::ObjectSerializer

  extend AvatarHelper # mixes in your helper method as class method

  set_type :user

  attributes :name, :email

  attribute :avatar do |user|
    avatar_url(user)
  end
end

两种写法的区别仅在于 mix-in 方式:include 配合 ActiveSupport::Concern 的 class_methods,或直接用 extend。属性块内部即可直接调用这些类方法。

十八、Customizable Options:关系与序列化器选项速查

README 汇总了所有可自定义选项,整理如下:

选项 用途 示例
set_type 对象的 Type 名称 set_type :movie
key 对象的键 belongs_to :owner, key: :user
set_id 对象的 ID set_id :owner_id 或 set_id { |record| "#{record.name.downcase}-#{record.id}" }
cache_options 启用缓存并设置缓存时长 cache_options enabled: true, cache_length: 12.hours, race_condition_ttl: 10.seconds
id_method_name 设置获取对象 ID 的自定义方法名(若关系传了块,则 id_method_name 作用于块的返回值而非资源对象本身) has_many :locations, id_method_name: :place_ids
object_method_name 设置获取关联对象的自定义方法名 has_many :locations, object_method_name: :places
record_type 为关系设置自定义 Object Type belongs_to :owner, record_type: :user
serializer 为关系设置自定义序列化器 has_many :actors, serializer: :custom_actor 或 has_many :actors, serializer: MyApp::Api::V1::ActorSerializer
polymorphic 允许多态关联出现不同的 record type has_many :targets, polymorphic: true
polymorphic 为多态关联中每个对象类设置自定义 record type has_many :targets, polymorphic: { Person => :person, Group => :group }

这些选项在 object_serializer.rb 的 create_relationship 与 fetch_polymorphic_option 中统一解析,最终封装为 relationship.rb 的 Relationship 对象。补充说明几点实现细节:

  • set_id 支持块:set_id { |record| ... } 会被保存为 Proc,id_from_record 检测到 Proc 时直接调用(见 serialization_core.rb);
  • serializer 的命名解析:传 Symbol 时,compute_serializer_name 会按当前序列化器的命名空间自动补全(例如在 MyApp::Api::V1 命名空间下,:custom_actor 会被解析为 MyApp::Api::V1::CustomActorSerializer,见 object_serializer.rb);
  • polymorphic: true 时,序列化器会按关联对象实际类的 demodulize.underscore 推导 record type(见 serialization_core.rb);传 Hash 时则按对象类精确匹配映射。多态关系的完整行为可参考 object_serializer_polymorphic_spec.rb。

十九、Instrumentation:ActiveSupport::Notifications 与 Skylight 集成

fast_jsonapi 内置了 Skylight 集成。启用方式是在 initializer 中添加:

require 'fast_jsonapi/instrumentation/skylight'

Skylight 依赖 ActiveSupport::Notifications 来追踪两个核心方法。如果不使用 Skylight、只想使用这些通知,则 require 插桩集成即可:

require 'fast_jsonapi/instrumentation'

被插桩的两个通知由以下两个常量提供(定义见 object_serializer.rb):

  • FastJsonapi::ObjectSerializer::SERIALIZABLE_HASH_NOTIFICATION(值为 'render.fast_jsonapi.serializable_hash')
  • FastJsonapi::ObjectSerializer::SERIALIZED_JSON_NOTIFICATION(值为 'render.fast_jsonapi.serialized_json')

也可以只插桩其中一个方法,使用下面任一 require:

require 'fast_jsonapi/instrumentation/serializable_hash'
require 'fast_jsonapi/instrumentation/serialized_json'

Skylight 集成同样支持按方法拆分:

require 'fast_jsonapi/instrumentation/skylight/normalizers/serializable_hash'
require 'fast_jsonapi/instrumentation/skylight/normalizers/serialized_json'

实现原理(见 instrumentation/serializable_hash.rb):serializable_hash 被 alias 为 serializable_hash_without_instrumentation,新方法体通过 ActiveSupport::Notifications.instrument(SERIALIZABLE_HASH_NOTIFICATION, { name: self.class.name }) 包裹原实现;Skylight 侧则通过 normalizers/serializable_hash.rb 注册通知常量并把类别映射为 view.render.fast_jsonapi.serializable_hash。相关规格见 normalizers_require_spec.rb 与 as_notifications_spec.rb。

二十、运行测试

项目使用 RSpec 测试,包含单元测试、功能测试与性能测试。运行全部测试:

rspec

跳过性能测试(更快):

rspec spec --tag ~performance:true

只运行性能测试:

rspec spec --tag performance:true

结语

fast_jsonapi 以 AMS 的声明式体验为入口,通过"单一职责 + 面向 JSON:API 规范定制 + 可选的极速 JSON 引擎"实现了数量级的序列化性能提升,其性能约束还被固化在 object_serializer_performance_spec.rb 中随每次变更回归验证。尽管项目官方已停止维护,但本文所覆盖的序列化器声明语法、关系/属性/链接/元信息定义、缓存与复合文档优化等设计思路,对理解 JSON:API 序列化器的实现与后续迁移到社区 fork 项目(jsonapi-serializer)仍有直接的参考价值。

登录后查看全文
fast_jsonapi