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

oat

> 编程语言
开源

基于适配器的 API 序列化器,为 Ruby 应用程序提供超媒体支持。

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

工具介绍

基于适配器的 API 序列化器,为 Ruby 应用程序提供超媒体支持。

Oat

Adapters-based API serializers with Hypermedia support for Ruby apps. Read the blog post for context and motivation.

What

Oat lets you design your API payloads succinctly while conforming to your media type of choice (hypermedia or not). The details of the media type are dealt with by pluggable adapters.

Oat ships with adapters for HAL, Siren and JsonAPI, and it's easy to write your own.

Serializers

A serializer describes one or more of your API's entities.

You extend from Oat::Serializer to define your own serializers.

ruby
require 'oat/adapters/hal'
class ProductSerializer < Oat::Serializer
  adapter Oat::Adapters::HAL

  schema do
    type "product"
    link :self, href: product_url(item)

    properties do |props|
      props.title item.title
      props.price item.price
      props.description item.blurb
    end
  end

end

Then in your app (for example a Rails controller)

ruby
product = Product.find(params[:id])
render json: ProductSerializer.new(product)

Serializers require a single object as argument, which can be a model instance, a presenter or any other domain object.

The full serializer signature is item, context, adapter_class.

  • item a model or presenter instance. It is available in your serializer's schema as item.
  • context (optional) a context hash that is passed to the serializer and sub-serializers as the context variable. Useful if you need to pass request-specific data.
  • adapter_class (optional) A serializer's adapter can be configured at class-level or passed here to the initializer. Useful if you want to switch adapters based on request data. More on this below.

Defining Properties

There are a few different ways of defining properties on a serializer.

Properties can be added explicitly using property. In this case, you can map an arbitrary value to an arbitrary key:

ruby
require 'oat/adapters/hal'
class ProductSerializer < Oat::Serializer
  adapter Oat::Adapters::HAL

  schema do
    type "product"
    link :self, href: product_url(item)

    property :title, item.title
    property :price, item.price
    property :description, item.blurb
    property :the_number_one, 1
  end
end

Similarly, properties can be added within a block using properties to be more concise or make the code more readable. Again, these will set arbitrary values for arbitrary keys:

ruby
require 'oat/adapters/hal'
class ProductSerializer < Oat::Serializer
  adapter Oat::Adapters::HAL

  schema do
    type "product"
    link :self, href: product_url(item)

    properties do |p|
      p.title           item.title
      p.price           item.price
      p.description     item.blurb
      p.the_number_one  1
    end
  end
end

In many cases, you will want to simply map the properties of item to a property in the serializer. This can be easily done using map_properties. This method takes a list of method or attribute names to which item will respond. Note that you cannot assign arbitrary values and keys using map_properties - the serializer will simply add a key and call that method on item to assign the value.

ruby
require 'oat/adapters/hal'
class ProductSerializer < Oat::Serializer
  adapter Oat::Adapters::HAL

  schema do
    type "product"
    link :self, href: product_url(item)

    map_properties :title, :price
    property :description, item.blurb
    property :the_number_one, 1
  end
end

Defining Links

Links to other resources can be added by using link with a name and an options hash. Most adapters expect just an href in the options hash, but some might support additional properties. Some adapters also suport passing templated: true in the options hash to indicate special treatment of a link template.

Adding meta-information

You can add meta-information about your JSON document via meta :property, "value". When using the JsonAPI adapter these properties are rendered in a top level "meta" node. When using the HAL or Siren adapters meta just acts as an alias to property, so the properties are rendered like normal properties.

Adapters

Using the included HAL adapter, the ProductSerializer above would render the following JSON:

json
{
    "_links": {
        "self": {"href": "http://example.com/products/1"}
    },
    "title": "Some product",
    "price": 1000,
    "description": "..."
}

You can easily swap adapters. The same ProductSerializer, this time using the Siren adapter:

ruby
adapter Oat::Adapters::Siren

... Renders this JSON:

json
{
    "class": ["product"],
    "links": [
        { "rel": [ "self" ], "href": "http://example.com/products/1" }
    ],
    "properties": {
        "title": "Some product",
        "price": 1000,
        "description": "..."
    }
}

At the moment Oat ships with adapters for HAL, Siren and JsonAPI, but it's easy to write your own.

Note: Oat adapters are not required by default. Your code should explicitly require the ones it needs:

ruby
# HAL
require 'oat/adapters/hal'
# Siren
require 'oat/adapters/siren'
# JsonAPI
require 'oat/adapters/json_api'

Switching adapters dynamically

Adapters can also be passed as an argument to serializer instances.

ruby
ProductSerializer.new(product, nil, Oat::Adapters::HAL)

That means that your app could switch adapters on run time depending, for example, on the request's Accept header or anything you need.

Note: a different library could be written to make adapter-switching auto-magical for different frameworks, for example using Responders in Rails. Also see Rails Integration.

Nested serializers

It's common for a media type to include "embedded" entities within a payload. For example an account entity may have many users. An Oat serializer can inline such relationships:

ruby
class AccountSerializer < Oat::Serializer
  adapter Oat::Adapters::HAL

  schema do
    property :id, item.id
    property :status, item.status
    # user entities
    entities :users, item.users do |user, user_serializer|
      user_serializer.properties do |props|
        props.name user.name
        props.email user.email
      end
    end
  end
end

Another, more reusable option is to use a nested serializer. Instead of a block, you pass another serializer class that will handle serializing user entities.

ruby
class AccountSerializer < Oat::Serializer
  adapter Oat::Adapters::HAL

  schema do
    property :id, item.id
    property :status, item.status
    # user entities
    entities :users, item.users, UserSerializer
  end
end

And the UserSerializer may look like this:

ruby
class UserSerializer < Oat::Serializer
  adapter Oat::Adapters::HAL

  schema do
    property :name, item.name
    property :email, item.name
  end
end

In the user serializer, item refers to the user instance being wrapped by the serializer.

The bundled hypermedia adapters ship with an entities method to add arrays of entities, and an entity method to add a single entity.

ruby
# single entity
entity :child, item.child do |child, s|
  s.name child.name
  s.id child.id
end

# list of entities
entities :children, item.children do |child, s|
  s.name child.name
  s.id child.id
end

Both can be expressed using a separate serializer:

ruby
# single entity
entity :child, item.child, ChildSerializer

# list of entities
entities :children, item.children, ChildSerializer

The way sub-entities are rendered in the final payload is up to the adapter. In HAL the example above would be:

json
{
  ...,
  "_embedded": {
    "child": {"name": "child's name", "id": 1},
    "children": [
      {"name": "child 2 name", "id": 2},
      {"name": "child 3 name", "id": 3},
      ...
    ]
  }
}

Nested serializers when using the JsonAPI adapter

Collections are easy to express in HAL and Siren because they're no different from any other "entity". JsonAPI, however, doesn't work that way. In JsonAPI there's a distinction between "side-loaded" entities and the collection that is the subject of the resource. For this reason a collection method was added to the Oat DSL specifically for use with the JsonAPI adapter.

In the HAL and Siren adapters, collection is aliased to entities, but in the JsonAPI adapter, it sets the resource's main collection array as per the spec. entities keep the current behaviour of side-loading entities in the resource.

Subclassing

Serializers can be subclassed, for example if you want all your serializers to share the same adapter or add shared helper methods.

ruby
class MyAppSerializer < Oat::Serializer
  adapter Oat::Adapters::HAL

  protected

  def format_price(price)
    Money.new(price, 'GBP').format
  end
end
ruby
class ProductSerializer < MyAppSerializer
  schema do
    property :title, item.title
    property :price, format_price(item.price)
  end
end

This is useful if you want your serializers to better express your app's domain. For example, a serializer for a social app:

ruby
class UserSerializer < SocialSerializer
  schema do
    name item.name
    email item.email
    # friend entities
    friends item.friends
  end
end

The superclass defines the methods name, email and friends, which in turn delegate to the adapter's setters.

ruby
class SocialSerializer < Oat::Serializer
  adapter Oat::Adapters::HAL # or whatever

  # friendly setters
  protected

  def name(value)
    property :name, value
  end

  def email(value)
    property :email, value
  end

  def friends(objects)
    entities :friends, objects, FriendSerializer
  end
end

You can specify multiple schema blocks, including across class hierarchies. This allows us to append schema attributes or override previously defined attributes:

ruby
class ExtendedUserSerializer < UserSerializer
  schema do
    name item.full_name # name property will now by the user's full name
    property :dob, item.dob # additional date of birth attribute
  end
end

URLs

Hypermedia is all about the URLs linking your resources together. Oat adapters can have methods to declare links in your entity schema but it's up to your code/framework how to create those links. A simple stand-alone implementation could be:

ruby
class ProductSerializer < Oat::Serializer
  adapter Oat::Adapters::HAL

  schema do
    link :self, href: product_url(item.id)
    ...
  end

  protected

  # helper URL method
  def product_url(id)
    "https://api.com/products/#{id}"
  end
end

In frameworks like Rails, you'll probably want to use the URL helpers created by the routes.rb file. Two options:

Pass a context hash to serializers

You can pass a context hash as second argument to serializers. This object will be passed to nested serializers too. For example, you can pass the controller instance itself.

ruby
# users_controller.rb

def show
  user = User.find(params[:id])
  render json: UserSerializer.new(user, controller: self)
end

Then, in the UserSerializer:

ruby
class ProductSerializer < Oat::Serializer
  adapter Oat::Adapters::HAL

  schema do
    # `context[:controller]` is the controller, which responds to URL helpers.
    link :self, href: context[:controller].product_url(item)
    ...
  end
end

The context hash is passed down to each nested serializer called by a parent. In some cases, you might want to include extra context information for one or more nested serializers. Thi

Issues· 12 开放

查看全部 Issues在 GitHub 打开

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

> 标签

Ruby

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

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言