Created
July 20, 2018 01:05
-
-
Save amyroi/3396e67be4c41aeff837fa0c0ccb3def to your computer and use it in GitHub Desktop.
ActiveModel::Serializer for ActiveModel::Model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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