Skip to content

Commit ea7ef99

Browse files
committed
Merge pull request #1432 from xhh/ruby-empty-array
Ruby client: include empty arrays in model serialization
2 parents 83afaff + dcec2e7 commit ea7ef99

File tree

3 files changed

+26
-14
lines changed

3 files changed

+26
-14
lines changed

modules/swagger-codegen/src/main/resources/ruby/base_object.mustache

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -60,14 +60,13 @@ module {{moduleName}}
6060
# return the object in the form of hash
6161
def to_hash
6262
hash = {}
63-
self.class.attribute_map.each_pair do |key, value|
64-
if self.send(key).is_a?(Array)
65-
next if self.send(key).empty?
66-
hash[value] = self.send(key).select{|v| !v.nil?}.map{ |v| _to_hash v} unless self.send(key).nil?
63+
self.class.attribute_map.each_pair do |attr, param|
64+
value = self.send(attr)
65+
next if value.nil?
66+
if value.is_a?(Array)
67+
hash[param] = value.compact.map{ |v| _to_hash(v) }
6768
else
68-
unless (_tmp_value = _to_hash self.send(key)).nil?
69-
hash[value] = _tmp_value
70-
end
69+
hash[param] = _to_hash(value)
7170
end
7271
end
7372
hash

samples/client/petstore/ruby/lib/petstore/models/base_object.rb

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -60,14 +60,13 @@ def to_body
6060
# return the object in the form of hash
6161
def to_hash
6262
hash = {}
63-
self.class.attribute_map.each_pair do |key, value|
64-
if self.send(key).is_a?(Array)
65-
next if self.send(key).empty?
66-
hash[value] = self.send(key).select{|v| !v.nil?}.map{ |v| _to_hash v} unless self.send(key).nil?
63+
self.class.attribute_map.each_pair do |attr, param|
64+
value = self.send(attr)
65+
next if value.nil?
66+
if value.is_a?(Array)
67+
hash[param] = value.compact.map{ |v| _to_hash(v) }
6768
else
68-
unless (_tmp_value = _to_hash self.send(key)).nil?
69-
hash[value] = _tmp_value
70-
end
69+
hash[param] = _to_hash(value)
7170
end
7271
end
7372
hash

samples/client/petstore/ruby/spec/api_client_spec.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,4 +102,18 @@
102102
end
103103
end
104104

105+
describe "#object_to_hash" do
106+
it "ignores nils and includes empty arrays" do
107+
api_client = Petstore::ApiClient.new
108+
pet = Petstore::Pet.new
109+
pet.id = 1
110+
pet.name = ''
111+
pet.status = nil
112+
pet.photo_urls = nil
113+
pet.tags = []
114+
expected = {id: 1, name: '', tags: []}
115+
api_client.object_to_hash(pet).should == expected
116+
end
117+
end
118+
105119
end

0 commit comments

Comments
 (0)