Created
October 24, 2017 03:01
-
-
Save arc279/35b1657b27e26eaa95097a070db5ebd1 to your computer and use it in GitHub Desktop.
nest of ActiveModel::Serializers::JSON (rails5)
This file contains hidden or 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
| 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