Support primitive response in Ruby client

This commit is contained in:
xhh
2015-07-08 16:46:31 +08:00
parent f42f329ace
commit a24fee00cb
2 changed files with 34 additions and 24 deletions

View File

@@ -40,25 +40,30 @@ module {{moduleName}}
end
begin
data = JSON.parse(body, :symbolize_names => true)
data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
rescue JSON::ParserError => e
if return_type == 'String'
return body
if %w(String Date DateTime).include?(return_type)
data = body
else
raise e
end
end
build_models data, return_type
convert_to_type data, return_type
end
# Walk through the given data and, when necessary, build model(s) from
# Hash data for array/hash values of the response.
def build_models(data, return_type)
# Convert data to the given return type.
def convert_to_type(data, return_type)
return nil if data.nil?
case return_type
when 'String', 'Integer', 'Float', 'BOOLEAN'
# primitives, return directly
data
when 'String'
data.to_s
when 'Integer'
data.to_i
when 'Float'
data.to_f
when 'BOOLEAN'
data == true
when 'DateTime'
# parse date time (expecting ISO 8601 format)
DateTime.parse data
@@ -71,12 +76,12 @@ module {{moduleName}}
when /\AArray<(.+)>\z/
# e.g. Array<Pet>
sub_type = $1
data.map {|item| build_models(item, sub_type) }
data.map {|item| convert_to_type(item, sub_type) }
when /\AHash\<String, (.+)\>\z/
# e.g. Hash<String, Integer>
sub_type = $1
{}.tap do |hash|
data.each {|k, v| hash[k] = build_models(v, sub_type) }
data.each {|k, v| hash[k] = convert_to_type(v, sub_type) }
end
else
# models, e.g. Pet

View File

@@ -40,25 +40,30 @@ module Petstore
end
begin
data = JSON.parse(body, :symbolize_names => true)
data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
rescue JSON::ParserError => e
if return_type == 'String'
return body
if %w(String Date DateTime).include?(return_type)
data = body
else
raise e
end
end
build_models data, return_type
convert_to_type data, return_type
end
# Walk through the given data and, when necessary, build model(s) from
# Hash data for array/hash values of the response.
def build_models(data, return_type)
# Convert data to the given return type.
def convert_to_type(data, return_type)
return nil if data.nil?
case return_type
when 'String', 'Integer', 'Float', 'BOOLEAN'
# primitives, return directly
data
when 'String'
data.to_s
when 'Integer'
data.to_i
when 'Float'
data.to_f
when 'BOOLEAN'
data == true
when 'DateTime'
# parse date time (expecting ISO 8601 format)
DateTime.parse data
@@ -71,12 +76,12 @@ module Petstore
when /\AArray<(.+)>\z/
# e.g. Array<Pet>
sub_type = $1
data.map {|item| build_models(item, sub_type) }
data.map {|item| convert_to_type(item, sub_type) }
when /\AHash\<String, (.+)\>\z/
# e.g. Hash<String, Integer>
sub_type = $1
{}.tap do |hash|
data.each {|k, v| hash[k] = build_models(v, sub_type) }
data.each {|k, v| hash[k] = convert_to_type(v, sub_type) }
end
else
# models, e.g. Pet