#363 - Add convenience methods for json parsing/formatting to generated objects

This commit is contained in:
Steve Bazyl 2016-02-25 14:37:00 -08:00
parent 07ca6e8ca0
commit 47a02e897e
3 changed files with 72 additions and 0 deletions

View File

@ -122,6 +122,24 @@ module Google
include Representable::JSON
feature JsonRepresentationSupport
end
module JsonObjectSupport
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def from_json(json)
representation = self.const_get(:Representation)
representation.new(self.new).from_json(json, unwrap: self)
end
end
def to_json
representation = self.class.const_get(:Representation)
representation.new(self).to_json(skip_undefined: true)
end
end
end
end
end

View File

@ -7,6 +7,8 @@ class <%= cls.generated_class_name %>
<%= indent(include('representation_stub', :cls => child_class), 2) -%>
<% end -%>
<% end -%>
include Google::Apis::Core::JsonObjectSupport
end
<% elsif cls.items && cls.items._ref.nil? -%>
<%= include('representation_stub', :cls => cls.items, :api => api) -%>

View File

@ -120,6 +120,58 @@ RSpec.describe Google::Apis::Generator do
it 'should define subresource methods' do
expect(service.method(:list_thing_subthings)).to_not be_nil
end
context 'With the from_json method' do
let(:json) do
<<EOF
{
"name" : "A thing",
"properties": {
"prop_a" : "value_a"
},
"photo": {
"filename": "image.jpg"
},
"hat": {
"type": "topHat",
"height": 100
}
}
EOF
end
let(:thing) { Google::Apis::TestV1::Thing.from_json(json) }
it 'should return a thing' do
expect(thing).to be_instance_of(Google::Apis::TestV1::Thing)
end
it 'should parse properties' do
expect(thing.name).to eq 'A thing'
end
it 'should parse subtypes' do
expect(thing.photo.filename).to eq "image.jpg"
end
end
context 'With the to_json method' do
let(:thing) do
Google::Apis::TestV1::Thing.new(
name: "A thing",
properties: {
prop_a: "value_a"
},
photo: {
filename: "image.jpg"
},
hat: {
type: "topHat",
height: 100
}
)
end
end
end
context 'with the get_thing method' do