Migrating from ActiveModelSerializers to Representable

Nadiya Karachevska
Nov 14, 2018 · 3 min read

Inheritance

class WidgetSerializer < ActiveModel::Serializer
end
class ApplicationSerializer < Representable::Decorator
include Representable::JSON
end
class WidgetSerializer < ApplicationSerializer
end

Rendering JSON

class WidgetsController < ApplicationController
def show
widget = Widget.find(params[:id])
render json: widget
end
end
class WidgetsController < ApplicationController
def show
widget = Widget.find(params[:id])
render json: WidgetSerializer.new(widget)
end
end

Attributes

class WidgetSerializer < ActiveModel::Serializer
attributes :id, :name
end
class WidgetSerializer < ApplicationSerializer
property :id
property :name
end
class WidgetSerializer < ApplicationSerializer
attributes :id, :name
def name
object.title
end
end

class WidgetSerializer < ApplicationSerializer
property :id
property :name, exec_context: :decorator
def name
represented.title
end
end

Wrapping

class WidgetSerializer < ApplicationSerializer
root :data
end
class WidgetSerializer < ApplicationSerializer
self.representation_wrap = :data
end
class WidgetSerializer < ApplicationSerializer
self.representation_wrap = ->(user_options:) do
user_options[:my_wrap] || :data
end
end
# wrap object with 'widget'
WidgetSerializer.new(widget).to_json(
user_options: { my_wrap: 'widget' }
)
# do not wrap the object
WidgetSerializer.new(widget).to_json(
user_options: { my_wrap: false }
)
# wrap the object with default 'data'
WidgetSerializer.new(widget).to_json

Associations

class WidgetSerializer < ApplicationSerializer
has_one :category, serializer: CategorySerializer
has_many :sources, each_serializer: SourceSerializer
end
class WidgetSerializer < ApplicationSerializer
property :category, decorator: CategorySerializer, wrap: false
collection :sources, decorator: SourceSerializer
end

ActiveModelSerializers magic

class WidgetSerializer < ApplicationSerializer
end
render json: widgets, each_serializer: WidgetSerializer
class WidgetsSerializer < ApplicationSerializer
collection :data, exec_context: :decorator,
decorator: WidgetSerializer, wrap: false
def data
represented
end
end
render json: WidgetsSerializer.new(widgets)

External parameter

class WidgetSerializer < ApplicationSerializer
attributes :id, :meta
attribute :name, if: :include_name?
def meta
options[:meta]
end
def include_name?
options[:include_name]
end
end
render json: widgets, meta: meta, include_name: true
class WidgetsSerializer < ApplicationSerializer
property :name, if: ->(user_options:, **) do
user_options[:include_name]
end
property :meta, getter: ->(user_options:, **) do
user_options[:meta]
end
end
render json: WidgetsSerializer.new(widgets).to_json(
user_options: { meta: meta, include_name: true }
)

Innocode Stories

Posts by folks who make Innocode

Nadiya Karachevska

Written by

Innocode Stories

Posts by folks who make Innocode