Skip to content

Instantly share code, notes, and snippets.

@arc279
Created October 24, 2017 03:01
Show Gist options
  • Save arc279/35b1657b27e26eaa95097a070db5ebd1 to your computer and use it in GitHub Desktop.
Save arc279/35b1657b27e26eaa95097a070db5ebd1 to your computer and use it in GitHub Desktop.
nest of ActiveModel::Serializers::JSON (rails5)
class Bar
include ActiveModel::Model
attr_accessor :foo, :bar
end
class Foo
include ActiveModel::Model
include ActiveModel::Serializers::JSON
attr_accessor :foo, :bar
def attributes=(hash)
@foo = hash["foo"]
@bar = Bar.new(hash["bar"])
end
def attributes
{foo: @foo, bar: @bar}
end
end
class Hoge
include ActiveModel::Model
include ActiveModel::Serializers::JSON
attr_accessor :foo, :bar
def attributes=(hash)
@foo = Foo.new.from_json(hash["foo"].to_json)
@bar = hash["bar"]
end
def attributes
{foo: @foo, bar: @bar}
end
end
a = Hoge.new(foo: Foo.new(foo: 234, bar: Bar.new(foo: 345, bar: 456)), bar: 123)
pp a
j = a.to_json
puts s
pp JSON.parse(j)
puts '----------------------------'
b = Hoge.new.from_json(j)
pp b
pp b.to_json
pp JSON.parse(b.to_json)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment