From 47a02e897e3e571b4e6f7f57e271e6ae59389089 Mon Sep 17 00:00:00 2001 From: Steve Bazyl Date: Thu, 25 Feb 2016 14:37:00 -0800 Subject: [PATCH] #363 - Add convenience methods for json parsing/formatting to generated objects --- lib/google/apis/core/json_representation.rb | 18 +++++++ .../templates/_representation_stub.tmpl | 2 + spec/google/apis/generator/generator_spec.rb | 52 +++++++++++++++++++ 3 files changed, 72 insertions(+) diff --git a/lib/google/apis/core/json_representation.rb b/lib/google/apis/core/json_representation.rb index ab28e04e1..4c78d361f 100644 --- a/lib/google/apis/core/json_representation.rb +++ b/lib/google/apis/core/json_representation.rb @@ -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 diff --git a/lib/google/apis/generator/templates/_representation_stub.tmpl b/lib/google/apis/generator/templates/_representation_stub.tmpl index b80cf6932..8882f2e04 100644 --- a/lib/google/apis/generator/templates/_representation_stub.tmpl +++ b/lib/google/apis/generator/templates/_representation_stub.tmpl @@ -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) -%> diff --git a/spec/google/apis/generator/generator_spec.rb b/spec/google/apis/generator/generator_spec.rb index a771d80d4..07dd53283 100644 --- a/spec/google/apis/generator/generator_spec.rb +++ b/spec/google/apis/generator/generator_spec.rb @@ -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 + <