百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
O

oj_serializers

> 数据库
开源

⚡️ 为 Ruby on Rails 提供更快的 JSON 序列化。轻松地从 Active Model Serializers 迁移。

166 stars0 点赞2 次浏览
访问官网GitHub

工具介绍

⚡️ 为 Ruby on Rails 提供更快的 JSON 序列化。轻松地从 Active Model Serializers 迁移。

Oj Serializers

Faster JSON serializers for Ruby, built on top of the powerful oj library.

Why?

ActiveModel::Serializer has a nice DSL, but it allocates many objects leading to memory bloat, time spent on GC, and lower performance.

Oj::Serializer provides a similar API, with better performance.

Learn more about how this library achieves its performance.

Features ⚡️

  • Intuitive declaration syntax, supporting mixins and inheritance
  • Reduced memory allocation and improved performance
  • Generate TypeScript interfaces automatically
  • Support for has_one and has_many, compose with flat_one
  • Useful development checks to avoid typos and mistakes
  • Migrate easily from Active Model Serializers

Installation

Add this line to your application's Gemfile:

ruby
gem 'oj_serializers'

And then run:

$ bundle install

Usage

You can define a serializer by subclassing Oj::Serializer, and specify which attributes should be serialized.

ruby
class AlbumSerializer 
  Example Output

```ruby
{
  name: "Abraxas",
  genres: [
    "Pyschodelic Rock",
    "Blues Rock",
    "Jazz Fusion",
    "Latin Rock",
  ],
  release: "September 23, 1970",
  songs: [
    {
      track: 1,
      name: "Sing Winds, Crying Beasts",
      composers: ["Michael Carabello"],
    },
    {
      track: 2,
      name: "Black Magic Woman / Gypsy Queen",
      composers: ["Peter Green", "Gábor Szabó"],
    },
    {
      track: 3,
      name: "Oye como va",
      composers: ["Tito Puente"],
    },
    {
      track: 4,
      name: "Incident at Neshabur",
      composers: ["Alberto Gianquinto", "Carlos Santana"],
    },
    {
      track: 5,
      name: "Se acabó",
      composers: ["José Areas"],
    },
    {
      track: 6,
      name: "Mother's Daughter",
      composers: ["Gregg Rolie"],
    },
    {
      track: 7,
      name: "Samba pa ti",
      composers: ["Santana"],
    },
    {
      track: 8,
      name: "Hope You're Feeling Better",
      composers: ["Rolie"],
    },
    {
      track: 9,
      name: "El Nicoya",
      composers: ["Areas"],
    },
  ],
}

You can then use your new serializer to render an object or collection:

ruby
class AlbumsController 
  Active Model Serializers style

```ruby
require "oj_serializers/sugar" # In an initializer

class AlbumsController 

## Rendering 

Use `one` to serialize objects, and `many` to serialize enumerables:

```ruby
render json: {
  favorite_album: AlbumSerializer.one(album),
  purchased_albums: AlbumSerializer.many(albums),
}

Serializers can be rendered arrays, hashes, or even inside ActiveModel::Serializer by using a method in the serializer, making it very easy to combine with other libraries and migrate incrementally.

render is a shortcut for one and many:

ruby
render json: {
  favorite_album: AlbumSerializer.render(album),
  purchased_albums: AlbumSerializer.render(albums),
}

Attributes DSL

Specify which attributes should be rendered by calling a method in the object to serialize.

ruby
class PlayerSerializer  **Note**
>
> In this example, `player` was inferred from `PlayerSerializer`.
>
> You can customize this by using [`object_as`](#using-a-different-alias-for-the-internal-object).

### Associations 

Use `has_one` to serialize individual objects, and `has_many` to serialize a collection.

You must specificy which serializer to use with the `serializer` option.

```ruby
class SongSerializer  { player.display_name? }

  has_one :album, serializer: AlbumSerializer, if: -> { player.album }
end

This is useful in cases where you don't want to null values to be in the response.

Advanced Usage ‍♂️

Using a different alias for the internal object

In most cases, the default alias for the object will be convenient enough.

However, if you would like to specify it manually, use object_as:

ruby
class DiscographySerializer  (key) { key.to_s.camelize(:lower) }
end

This has no performance impact, as keys will be transformed at load time.

Sorting attributes

By default attributes are rendered in the order they are defined.

If you would like to sort attributes alphabetically, you can specify it at a serializer level:

ruby
class BaseSerializer 
  Example Output

```ruby
{
  id: 5,
  filename: "image.jpg,
  byte_size: 256074,
  content_type: "image/jpeg",
  created_at: "2022-08-04T17:25:12.637-07:00",
}

This is especially convenient when using types_from_serializers, as it enables automatic type inference for the included attributes.

Memoization & local state

Serializers are designed to be stateless so that an instanced can be reused, but sometimes it's convenient to store intermediate calculations.

Use memo for memoization and storing temporary information.

ruby
class DownloadSerializer  'Mary', :middle_name => 'Jane', :last_name => 'Watson')
# {first_name: "Mary", last_name: "Watson"}

mongo_attributes

Reads data directly from attributes in a Mongoid document.

By skipping type casting, coercion, and defaults, it achieves the best performance.

Although there are some downsides, depending on how consistent your schema is, and which kind of consumer the API has, it can be really powerful.

ruby
class AlbumSerializer (user) {
    "#{ user.id }/#{ user.current_sign_in_at }"
  }
end

It will leverage fetch_multi when serializing a collection with many or has_many, to minimize the amount of round trips needed to read and write all items to cache.

This works specially well if your cache store also supports write_multi.

Writing to JSON

In some corner cases it might be faster to serialize using a Oj::StringWriter, which you can access by using one_as_json and many_as_json.

Alternatively, you can toggle this mode at a serializer level by using default_format :json, or configure it globally from your base serializer:

ruby
class BaseSerializer 
  Example Output

…


## Design 

Unlike `ActiveModel::Serializer`, which builds a Hash that then gets encoded to
JSON, this implementation can use `Oj::StringWriter` to write JSON directly,
greatly reducing the overhead of allocating and garbage collecting the hashes.

It also allocates a single instance per serializer class, which makes it easy
to use, while keeping memory usage under control.

The internal design is simple and extensible, and because the library is written
in Ruby, creating new serialization strategies requires very little code.
Please open a [Discussion] if you need help 

### Comparison with other libraries

`ActiveModel::Serializer` instantiates one serializer object per item to be serialized.

Other libraries such as [`blueprinter`][blueprinter] [`jsonapi-serializer`][jsonapi]
evaluate serializers in the context of a `class` instead of an `instance` of a class.
The downside is that you can't use instance methods or local memoization, and any
mixins must be applied to the class itself.

[`panko-serializer`][panko] also uses `Oj::StringWriter`, but it has the big downside of having to own the entire render tree. Putting a serializer inside a Hash or an Active Model Serializer and serializing that to JSON doesn't work, making a gradual migration harder to achieve. Also, it's optimized for Active Record but I needed good Mongoid support.

`Oj::Serializer` combines some of these ideas, by using instances, but reusing them to avoid object allocations. Serializing 10,000 items instantiates a single serializer. Unlike `panko-serializer`, it doesn't suffer from [double encoding problems](https://panko.dev/docs/response-bag) so it's easier to use.

Follow [this discussion][raw_json] to find out more about [the `raw_json` extensions][raw_json] that made this high level of interoperability possible.

As a result, migrating from `active_model_serializers` is relatively
straightforward because instance methods, inheritance, and mixins work as usual.

### Benchmarks 

This library includes some [benchmarks] to compare performance with similar libraries.

See [this pull request](https://github.com/ElMassimo/oj_serializers/pull/9) for a quick comparison,
or check the CI to see the latest results.

### Migrating from other libraries

Please refer to the [migration guide] for a full discussion of the compatibility
modes available to make it easier to migrate from `active_model_serializers` and
similar libraries.

## Formatting 

Even though most of the examples above use a single-line style to be succint, I highly recommend writing one attribute per line, sorting them alphabetically (most editors can do it for you), and [always using a trailing comma][trailing_commas].

```ruby
class AlbumSerializer < Oj::Serializer
  attributes(
    :genres,
    :name,
    :release_date,
  )
end

It will make things clearer, minimize the amount of git conflicts, and keep the history a lot cleaner and more meaningful when using git blame.

Special Thanks

This library wouldn't be possible without the wonderful and performant oj library. Thanks Peter!

Also, thanks to the libraries that inspired this one:

  • active_model_serializers: For the DSL
  • panko-serializer: For validating that using Oj::StringWriter was indeed fast

License

The gem is available as open source under the terms of the MIT License.

Issues· 8 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Rubyjsonjson-serializationojperformance

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类数据库
定价开源

> 相关工具

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库