Oj::Serializer
This guide covers using Typelizer with Oj::Serializer.
Setup
ruby
class ApplicationSerializer < Oj::Serializer
include Typelizer::DSL
endAttributes and Associations
Define attributes and associations as usual:
ruby
class PostSerializer < ApplicationSerializer
attributes :id, :title, :body
has_one :author, serializer: AuthorSerializer
has_many :comments, serializer: CommentSerializer
belongs_to :created_by, serializer: UserSerializer
endTypelizer infers types from the model. Use typelize_from when the model name can't be inferred:
ruby
class AuthorSerializer < ApplicationSerializer
typelize_from User
attributes :id, :name
endKey Transformation
Oj's transform_keys is respected:
ruby
class PostSerializer < ApplicationSerializer
transform_keys :camel_case
attributes :id, :title, :created_at
endFlat Associations
Oj::Serializer's flat_one inlines an association's attributes into the parent type alongside the nested reference:
ruby
class UserSerializer < ApplicationSerializer
attributes :id, :name
flat_one :invitor, serializer: UserSerializer
endThe invitor's attributes (username, active, name, etc.) are merged directly into the parent type. The invitor property itself is also kept in the output.
Conditional and Nullable Attributes
Oj::Serializer supports optional and nullable flags directly:
ruby
class PostSerializer < ApplicationSerializer
attributes :id, :title
attribute :draft, optional: true
attribute :deleted_at, nullable: true
endSee Manual Typing for full details on the typelize method.