Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amyroi/3396e67be4c41aeff837fa0c0ccb3def to your computer and use it in GitHub Desktop.
Save amyroi/3396e67be4c41aeff837fa0c0ccb3def to your computer and use it in GitHub Desktop.
ActiveModel::Serializer for ActiveModel::Model
# ActiveModel::SerializerをActiveModel::Modelで使う
class Model < ApplicationRecord
end
# Modelの操作をするクラス
class Dummy
include ActiveModel::Serialization
include ActiveModel::Model
attr_accessor :model
def model
@model ||= Model.new
end
end
class ModelSerializer < ActiveModel::Serializer
attributes :id, :state
end
# Dummyオブジェクト用のシリアライザ
class DummySerializer < ActiveModel::Serializer
# attributesのmodelをModelSerializerを通す。
has_one :model
end
a = Dummy.new
b = ModelSerializer.new(a)
b.to_json
=> "{\"model\":{\"id\":\"f7e80d4a-be60-4475-897e-4ae47132b4b1\",\"state\":0}}"
b.as_json
=> {:model=>{:id=>"f7e80d4a-be60-4475-897e-4ae47132b4b1", :state=>0}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment