Ruby client: include empty arrays in model serialization

This commit is contained in:
xhh 2015-10-23 17:08:12 +08:00
parent a6e4203cd5
commit 940e76f45f
3 changed files with 26 additions and 14 deletions

View File

@ -60,14 +60,13 @@ module {{moduleName}}
# return the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |key, value|
if self.send(key).is_a?(Array)
next if self.send(key).empty?
hash[value] = self.send(key).select{|v| !v.nil?}.map{ |v| _to_hash v} unless self.send(key).nil?
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
if value.is_a?(Array)
hash[param] = value.compact.map{ |v| _to_hash(v) }
else
unless (_tmp_value = _to_hash self.send(key)).nil?
hash[value] = _tmp_value
end
hash[param] = value
end
end
hash

View File

@ -60,14 +60,13 @@ module Petstore
# return the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |key, value|
if self.send(key).is_a?(Array)
next if self.send(key).empty?
hash[value] = self.send(key).select{|v| !v.nil?}.map{ |v| _to_hash v} unless self.send(key).nil?
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
if value.is_a?(Array)
hash[param] = value.compact.map{ |v| _to_hash(v) }
else
unless (_tmp_value = _to_hash self.send(key)).nil?
hash[value] = _tmp_value
end
hash[param] = value
end
end
hash

View File

@ -102,4 +102,18 @@ describe Petstore::ApiClient do
end
end
describe "#object_to_hash" do
it "ignores nils and includes empty arrays" do
api_client = Petstore::ApiClient.new
pet = Petstore::Pet.new
pet.id = 1
pet.name = ''
pet.status = nil
pet.photo_urls = nil
pet.tags = []
expected = {id: 1, name: '', tags: []}
api_client.object_to_hash(pet).should == expected
end
end
end