From 3de42afed344720463f73821a60f8970b6644b4b Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 15 Jul 2015 15:24:31 +0800 Subject: [PATCH 01/17] Implement API client structure for Ruby client --- .../codegen/languages/RubyClientCodegen.java | 20 ++++++------- .../src/main/resources/ruby/api.mustache | 30 +++++++++++-------- .../{swagger_client.mustache => gem.mustache} | 0 ...ient.gemspec.mustache => gemspec.mustache} | 0 4 files changed, 27 insertions(+), 23 deletions(-) rename modules/swagger-codegen/src/main/resources/ruby/{swagger_client.mustache => gem.mustache} (100%) rename modules/swagger-codegen/src/main/resources/ruby/{swagger_client.gemspec.mustache => gemspec.mustache} (100%) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java index 716c1bb0870..352307220a6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java @@ -105,17 +105,15 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { setModelPackage("models"); setApiPackage("api"); - supportingFiles.add(new SupportingFile("swagger_client.gemspec.mustache", "", gemName + ".gemspec")); - supportingFiles.add(new SupportingFile("swagger_client.mustache", libFolder, gemName + ".rb")); - String baseFolder = libFolder + File.separator + gemName; - supportingFiles.add(new SupportingFile("swagger.mustache", baseFolder, "swagger.rb")); - String swaggerFolder = baseFolder + File.separator + "swagger"; - supportingFiles.add(new SupportingFile("swagger" + File.separator + "request.mustache", swaggerFolder, "request.rb")); - supportingFiles.add(new SupportingFile("swagger" + File.separator + "response.mustache", swaggerFolder, "response.rb")); - supportingFiles.add(new SupportingFile("swagger" + File.separator + "api_error.mustache", swaggerFolder, "api_error.rb")); - supportingFiles.add(new SupportingFile("swagger" + File.separator + "version.mustache", swaggerFolder, "version.rb")); - supportingFiles.add(new SupportingFile("swagger" + File.separator + "configuration.mustache", swaggerFolder, "configuration.rb")); - String modelFolder = baseFolder + File.separator + modelPackage.replace("/", File.separator); + supportingFiles.add(new SupportingFile("gemspec.mustache", "", gemName + ".gemspec")); + supportingFiles.add(new SupportingFile("gem.mustache", libFolder, gemName + ".rb")); + String gemFolder = libFolder + File.separator + gemName; + supportingFiles.add(new SupportingFile("api_client.mustache", gemFolder, "api_client.rb")); + supportingFiles.add(new SupportingFile("request.mustache", gemFolder, "request.rb")); + supportingFiles.add(new SupportingFile("response.mustache", gemFolder, "response.rb")); + supportingFiles.add(new SupportingFile("api_error.mustache", gemFolder, "api_error.rb")); + supportingFiles.add(new SupportingFile("version.mustache", gemFolder, "version.rb")); + String modelFolder = gemFolder + File.separator + modelPackage.replace("/", File.separator); supportingFiles.add(new SupportingFile("base_object.mustache", modelFolder, "base_object.rb")); } diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index 612292b78ff..bc62a114050 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -3,6 +3,12 @@ require "uri" module {{moduleName}} {{#operations}} class {{classname}} + attr_accessor :api_client + + def initialize(api_client = ApiClient.new) + @api_client = api_client + end + {{#operation}} {{newline}} # {{summary}} @@ -11,9 +17,9 @@ module {{moduleName}} {{/required}}{{/allParams}} # @param [Hash] opts the optional parameters {{#allParams}}{{^required}} # @option opts [{{{dataType}}}] :{{paramName}} {{description}} {{/required}}{{/allParams}} # @return [{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}] - def self.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: {{classname}}#{{nickname}} ..." + def {{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {}) + if @client.debugging + @client.logger.debug "Calling API: {{classname}}#{{nickname}} ..." end {{#allParams}}{{#required}} # verify the required parameter '{{paramName}}' is set @@ -39,11 +45,11 @@ module {{moduleName}} # HTTP header 'Accept' (if needed) _header_accept = [{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type){{#headerParams}}{{#required}} + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type){{#headerParams}}{{#required}} header_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/headerParams}}{{#headerParams}}{{^required}} header_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/headerParams}} @@ -54,18 +60,18 @@ module {{moduleName}} # http body (model) {{^bodyParam}}post_body = nil - {{/bodyParam}}{{#bodyParam}}post_body = Swagger::Request.object_to_http_body({{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}) + {{/bodyParam}}{{#bodyParam}}post_body = Request.object_to_http_body({{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}) {{/bodyParam}} auth_names = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}] - {{#returnType}}response = Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + {{#returnType}}response = Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make result = response.deserialize('{{{returnType}}}') - if Swagger.configuration.debug - Swagger.logger.debug "API called: {{classname}}#{{nickname}}. Result: #{result.inspect}" + if @client.debugging + @client.logger.debug "API called: {{classname}}#{{nickname}}. Result: #{result.inspect}" end - result{{/returnType}}{{^returnType}}Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - if Swagger.configuration.debug - Swagger.logger.debug "API called: {{classname}}#{{nickname}}" + result{{/returnType}}{{^returnType}}Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @client.debugging + @client.logger.debug "API called: {{classname}}#{{nickname}}" end nil{{/returnType}} end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/gem.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache rename to modules/swagger-codegen/src/main/resources/ruby/gem.mustache diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger_client.gemspec.mustache b/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/ruby/swagger_client.gemspec.mustache rename to modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache From 4ecc757bea277a464efe8e8830256c86821d6acf Mon Sep 17 00:00:00 2001 From: xhh Date: Tue, 21 Jul 2015 17:07:41 +0800 Subject: [PATCH 02/17] More on API client structure for Ruby client --- .../main/resources/ruby/api_client.mustache | 77 +++++++ .../src/main/resources/ruby/gem.mustache | 16 +- .../src/main/resources/ruby/gemspec.mustache | 4 +- .../src/main/resources/ruby/request.mustache | 208 +++++++++++++++++ .../src/main/resources/ruby/swagger.mustache | 76 ------- .../resources/ruby/swagger/request.mustache | 214 ------------------ .../resources/ruby/swagger/version.mustache | 5 - .../src/main/resources/ruby/version.mustache | 3 + 8 files changed, 296 insertions(+), 307 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/ruby/api_client.mustache create mode 100644 modules/swagger-codegen/src/main/resources/ruby/request.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/ruby/swagger.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache create mode 100644 modules/swagger-codegen/src/main/resources/ruby/version.mustache diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache new file mode 100644 index 00000000000..8e295047dd9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache @@ -0,0 +1,77 @@ +require 'logger' +require 'json' + +module {{moduleName}} + class ApiClient + attr_accessor :logger + + # A Swagger configuration object. Must act like a hash and return sensible + # values for all Swagger configuration options. See Swagger::Configuration. + attr_accessor :configuration + + attr_accessor :resources + + # Call this method to modify defaults in your initializers. + # + # @example + # Swagger.configure do |config| + # config.api_key['api_key'] = '1234567890abcdef' # api key authentication + # config.username = 'wordlover' # http basic authentication + # config.password = 'i<3words' # http basic authentication + # config.format = 'json' # optional, defaults to 'json' + # end + # + def configure + yield(configuration) if block_given? + + self.logger = configuration.logger + + # remove :// from scheme + configuration.scheme.sub!(/:\/\//, '') + + # remove http(s):// and anything after a slash + configuration.host.sub!(/https?:\/\//, '') + configuration.host = configuration.host.split('/').first + + # Add leading and trailing slashes to base_path + configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/') + configuration.base_path = "" if configuration.base_path == "/" + end + + def authenticated? + !Swagger.configuration.auth_token.nil? + end + + def de_authenticate + Swagger.configuration.auth_token = nil + end + + def authenticate + return if Swagger.authenticated? + + if Swagger.configuration.username.nil? || Swagger.configuration.password.nil? + raise ApiError, "Username and password are required to authenticate." + end + + request = Swagger::Request.new( + :get, + "account/authenticate/{username}", + :params => { + :username => Swagger.configuration.username, + :password => Swagger.configuration.password + } + ) + + response_body = request.response.body + Swagger.configuration.auth_token = response_body['token'] + end + + def last_response + Thread.current[:swagger_last_response] + end + + def last_response=(response) + Thread.current[:swagger_last_response] = response + end + end +end diff --git a/modules/swagger-codegen/src/main/resources/ruby/gem.mustache b/modules/swagger-codegen/src/main/resources/ruby/gem.mustache index a43c8a9f6ea..41f151590d9 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/gem.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/gem.mustache @@ -1,10 +1,9 @@ -# Swagger common files -require '{{gemName}}/swagger' -require '{{gemName}}/swagger/configuration' -require '{{gemName}}/swagger/api_error' -require '{{gemName}}/swagger/request' -require '{{gemName}}/swagger/response' -require '{{gemName}}/swagger/version' +# Common files +require '{{gemName}}/api_client' +require '{{gemName}}/api_error' +require '{{gemName}}/request' +require '{{gemName}}/response' +require '{{gemName}}/version' # Models require '{{gemName}}/{{modelPackage}}/base_object' @@ -20,7 +19,4 @@ require '{{importPath}}' {{/apiInfo}} module {{moduleName}} - # Initialize the default configuration - Swagger.configuration = Swagger::Configuration.new - Swagger.configure { |config| } end diff --git a/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache b/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache index 38d70c07dd5..5c9c1c1a497 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache @@ -1,10 +1,10 @@ # -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) -require "{{gemName}}/swagger/version" +require "{{gemName}}/version" Gem::Specification.new do |s| s.name = "{{gemName}}" - s.version = {{moduleName}}::Swagger::VERSION + s.version = {{moduleName}}::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Zeke Sikelianos", "Tony Tam"] s.email = ["zeke@wordnik.com", "fehguy@gmail.com"] diff --git a/modules/swagger-codegen/src/main/resources/ruby/request.mustache b/modules/swagger-codegen/src/main/resources/ruby/request.mustache new file mode 100644 index 00000000000..c3de5843483 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/request.mustache @@ -0,0 +1,208 @@ +require 'uri' +require 'typhoeus' + +module {{moduleName}} + class Request + attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params, :auth_names, :response + + # All requests must have an HTTP method and a path + # Optionals parameters are :params, :headers, :body, :format, :host + def initialize(api_client, http_method, path, attributes = {}) + @api_client = api_client + + @http_method = http_method.to_sym.downcase + @path = path + + attributes.each { |name, value| send "#{name}=", value } + + @format ||= @api_client.format + @params ||= {} + + # Apply default headers + @headers = @api_client.default_headers.merge(@headers || {}) + {{#hasAuthMethods}} + update_params_for_auth! + {{/hasAuthMethods}} + end + + {{#hasAuthMethods}} + # Update hearder and query params based on authentication settings. + def update_params_for_auth! + (@auth_names || []).each do |auth_name| + case auth_name + {{#authMethods}}when '{{name}}' + {{#isApiKey}}{{#isKeyInHeader}}@headers ||= {} + @headers['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInHeader}}{{#isKeyInQuery}}@params ||= {} + @params['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}@headers ||= {} + http_auth_header = 'Basic ' + ["#{@api_client.username}:#{@api_client.password}"].pack('m').delete("\r\n") + @headers['Authorization'] = http_auth_header{{/isBasic}}{{#isOAuth}}# TODO: support oauth{{/isOAuth}} + {{/authMethods}} + end + end + end + {{/hasAuthMethods}} + + # Get API key (with prefix if set). + # @param [String] param_name the parameter name of API key auth + def get_api_key_with_prefix(param_name) + if @api_client.api_key_prefix[param_name] + "#{@api_client.api_key_prefix[param_name]} #{@api_client.api_key[param_name]}" + else + @api_client.api_key[param_name] + end + end + + # Construct the request URL. + def url(options = {}) + _path = self.interpreted_path + _path = "/#{_path}" unless _path.start_with?('/') + "#{@api_client.scheme}://#{@api_client.host}#{_path}" + end + + # Iterate over the params hash, injecting any path values into the path string + # e.g. /word.{format}/{word}/entries => /word.json/cat/entries + def interpreted_path + p = self.path.dup + + # Stick a .{format} placeholder into the path if there isn't + # one already or an actual format like json or xml + # e.g. /words/blah => /words.{format}/blah + if @api_client.inject_format + unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } + p = p.sub(/^(\/?\w+)/, "\\1.#{format}") + end + end + + # Stick a .{format} placeholder on the end of the path if there isn't + # one already or an actual format like json or xml + # e.g. /words/blah => /words/blah.{format} + if @api_client.force_ending_format + unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } + p = "#{p}.#{format}" + end + end + + p = p.sub("{format}", self.format.to_s) + + URI.encode [@api_client.base_path, p].join("/").gsub(/\/+/, '/') + end + + # If body is an object, JSONify it before making the actual request. + # For form parameters, remove empty value + def outgoing_body + # http form + if headers['Content-Type'] == 'application/x-www-form-urlencoded' + data = form_params.dup + data.each do |key, value| + data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter + end + elsif @body # http body is JSON + data = @body.is_a?(String) ? @body : @body.to_json + else + data = nil + end + + if @api_client.debugging + @api_client.logger.debug "HTTP request body param ~BEGIN~\n#{data}\n~END~\n" + end + + data + end + + def make + request_options = { + :method => self.http_method, + :headers => self.headers, + :params => self.params, + :ssl_verifypeer => @api_client.verify_ssl, + :cainfo => @api_client.ssl_ca_cert, + :verbose => @api_client.debugging + } + + if [:post, :patch, :put, :delete].include?(self.http_method) + request_options.update :body => self.outgoing_body + end + + raw = Typhoeus::Request.new(self.url, request_options).run + @response = Response.new(raw) + + if @api_client.debugging + @api_client.logger.debug "HTTP response body ~BEGIN~\n#{@response.body}\n~END~\n" + end + + # record as last response + @api_client.last_response = @response + + unless @response.success? + fail ApiError.new(:code => @response.code, + :response_headers => @response.headers, + :response_body => @response.body), + @response.status_message + end + + @response + end + + def response_code_pretty + return unless @response + @response.code.to_s + end + + def response_headers_pretty + return unless @response + # JSON.pretty_generate(@response.headers).gsub(/\n/, '
') # <- This was for RestClient + @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus + end + + # return 'Accept' based on an array of accept provided + # @param [Array] header_accept_array Array fo 'Accept' + # @return String Accept (e.g. application/json) + def self.select_header_accept header_accept_array + if header_accept_array.empty? + return + elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 } + 'application/json' # look for json data by default + else + header_accept_array.join(',') + end + end + + # return the content type based on an array of content-type provided + # @param [Array] content_type_array Array fo content-type + # @return String Content-Type (e.g. application/json) + def self.select_header_content_type content_type_array + if content_type_array.empty? + 'application/json' # use application/json by default + elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 } + 'application/json' # use application/json if it's included + else + content_type_array[0]; # otherwise, use the first one + end + end + + # static method to convert object (array, hash, object, etc) to JSON string + # @param model object to be converted into JSON string + # @return string JSON string representation of the object + def self.object_to_http_body model + return if model.nil? + _body = nil + if model.is_a?(Array) + _body = model.map{|m| object_to_hash(m) } + else + _body = object_to_hash(model) + end + _body.to_json + end + + # static method to convert object(non-array) to hash + # @param obj object to be converted into JSON string + # @return string JSON string representation of the object + def self.object_to_hash obj + if obj.respond_to?(:to_hash) + obj.to_hash + else + obj + end + end + end +end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache deleted file mode 100644 index 9be82e015cd..00000000000 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache +++ /dev/null @@ -1,76 +0,0 @@ -module {{moduleName}} - module Swagger - class << self - attr_accessor :logger - - # A Swagger configuration object. Must act like a hash and return sensible - # values for all Swagger configuration options. See Swagger::Configuration. - attr_accessor :configuration - - attr_accessor :resources - - # Call this method to modify defaults in your initializers. - # - # @example - # Swagger.configure do |config| - # config.api_key['api_key'] = '1234567890abcdef' # api key authentication - # config.username = 'wordlover' # http basic authentication - # config.password = 'i<3words' # http basic authentication - # config.format = 'json' # optional, defaults to 'json' - # end - # - def configure - yield(configuration) if block_given? - - self.logger = configuration.logger - - # remove :// from scheme - configuration.scheme.sub!(/:\/\//, '') - - # remove http(s):// and anything after a slash - configuration.host.sub!(/https?:\/\//, '') - configuration.host = configuration.host.split('/').first - - # Add leading and trailing slashes to base_path - configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/') - configuration.base_path = "" if configuration.base_path == "/" - end - - def authenticated? - !Swagger.configuration.auth_token.nil? - end - - def de_authenticate - Swagger.configuration.auth_token = nil - end - - def authenticate - return if Swagger.authenticated? - - if Swagger.configuration.username.nil? || Swagger.configuration.password.nil? - raise ApiError, "Username and password are required to authenticate." - end - - request = Swagger::Request.new( - :get, - "account/authenticate/{username}", - :params => { - :username => Swagger.configuration.username, - :password => Swagger.configuration.password - } - ) - - response_body = request.response.body - Swagger.configuration.auth_token = response_body['token'] - end - - def last_response - Thread.current[:swagger_last_response] - end - - def last_response=(response) - Thread.current[:swagger_last_response] = response - end - end - end -end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache deleted file mode 100644 index dd39449e1f3..00000000000 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache +++ /dev/null @@ -1,214 +0,0 @@ -require 'uri' -require 'typhoeus' - -module {{moduleName}} - module Swagger - class Request - attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params, :auth_names, :response - - # All requests must have an HTTP method and a path - # Optionals parameters are :params, :headers, :body, :format, :host - def initialize(http_method, path, attributes = {}) - @http_method = http_method.to_sym.downcase - @path = path - - attributes.each { |name, value| send "#{name}=", value } - - @format ||= Swagger.configuration.format - @params ||= {} - - # Apply default headers - @headers = Swagger.configuration.default_headers.merge(@headers || {}) - - # Stick in the auth token if there is one - if Swagger.authenticated? - @headers.merge!({:auth_token => Swagger.configuration.auth_token}) - end - {{#hasAuthMethods}} - update_params_for_auth! - {{/hasAuthMethods}} - end - - {{#hasAuthMethods}} - # Update hearder and query params based on authentication settings. - def update_params_for_auth! - (@auth_names || []).each do |auth_name| - case auth_name - {{#authMethods}}when '{{name}}' - {{#isApiKey}}{{#isKeyInHeader}}@headers ||= {} - @headers['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInHeader}}{{#isKeyInQuery}}@params ||= {} - @params['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}@headers ||= {} - http_auth_header = 'Basic ' + ["#{Swagger.configuration.username}:#{Swagger.configuration.password}"].pack('m').delete("\r\n") - @headers['Authorization'] = http_auth_header{{/isBasic}}{{#isOAuth}}# TODO: support oauth{{/isOAuth}} - {{/authMethods}} - end - end - end - {{/hasAuthMethods}} - - # Get API key (with prefix if set). - # @param [String] param_name the parameter name of API key auth - def get_api_key_with_prefix(param_name) - if Swagger.configuration.api_key_prefix[param_name] - "#{Swagger.configuration.api_key_prefix[param_name]} #{Swagger.configuration.api_key[param_name]}" - else - Swagger.configuration.api_key[param_name] - end - end - - # Construct the request URL. - def url(options = {}) - _path = self.interpreted_path - _path = "/#{_path}" unless _path.start_with?('/') - "#{Swagger.configuration.scheme}://#{Swagger.configuration.host}#{_path}" - end - - # Iterate over the params hash, injecting any path values into the path string - # e.g. /word.{format}/{word}/entries => /word.json/cat/entries - def interpreted_path - p = self.path.dup - - # Stick a .{format} placeholder into the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words.{format}/blah - if Swagger.configuration.inject_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = p.sub(/^(\/?\w+)/, "\\1.#{format}") - end - end - - # Stick a .{format} placeholder on the end of the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words/blah.{format} - if Swagger.configuration.force_ending_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = "#{p}.#{format}" - end - end - - p = p.sub("{format}", self.format.to_s) - - URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/') - end - - # If body is an object, JSONify it before making the actual request. - # For form parameters, remove empty value - def outgoing_body - # http form - if headers['Content-Type'] == 'application/x-www-form-urlencoded' - data = form_params.dup - data.each do |key, value| - data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter - end - elsif @body # http body is JSON - data = @body.is_a?(String) ? @body : @body.to_json - else - data = nil - end - - if Swagger.configuration.debug - Swagger.logger.debug "HTTP request body param ~BEGIN~\n#{data}\n~END~\n" - end - - data - end - - def make - request_options = { - :method => self.http_method, - :headers => self.headers, - :params => self.params, - :ssl_verifypeer => Swagger.configuration.verify_ssl, - :cainfo => Swagger.configuration.ssl_ca_cert, - :verbose => Swagger.configuration.debug - } - - if [:post, :patch, :put, :delete].include?(self.http_method) - request_options.update :body => self.outgoing_body - end - - raw = Typhoeus::Request.new(self.url, request_options).run - @response = Response.new(raw) - - if Swagger.configuration.debug - Swagger.logger.debug "HTTP response body ~BEGIN~\n#{@response.body}\n~END~\n" - end - - # record as last response - Swagger.last_response = @response - - unless @response.success? - fail ApiError.new(:code => @response.code, - :response_headers => @response.headers, - :response_body => @response.body), - @response.status_message - end - - @response - end - - def response_code_pretty - return unless @response - @response.code.to_s - end - - def response_headers_pretty - return unless @response - # JSON.pretty_generate(@response.headers).gsub(/\n/, '
') # <- This was for RestClient - @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus - end - - # return 'Accept' based on an array of accept provided - # @param [Array] header_accept_array Array fo 'Accept' - # @return String Accept (e.g. application/json) - def self.select_header_accept header_accept_array - if header_accept_array.empty? - return - elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # look for json data by default - else - header_accept_array.join(',') - end - end - - # return the content type based on an array of content-type provided - # @param [Array] content_type_array Array fo content-type - # @return String Content-Type (e.g. application/json) - def self.select_header_content_type content_type_array - if content_type_array.empty? - 'application/json' # use application/json by default - elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # use application/json if it's included - else - content_type_array[0]; # otherwise, use the first one - end - end - - # static method to convert object (array, hash, object, etc) to JSON string - # @param model object to be converted into JSON string - # @return string JSON string representation of the object - def self.object_to_http_body model - return if model.nil? - _body = nil - if model.is_a?(Array) - _body = model.map{|m| object_to_hash(m) } - else - _body = object_to_hash(model) - end - _body.to_json - end - - # static method to convert object(non-array) to hash - # @param obj object to be converted into JSON string - # @return string JSON string representation of the object - def self.object_to_hash obj - if obj.respond_to?(:to_hash) - obj.to_hash - else - obj - end - end - - end - end -end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache deleted file mode 100644 index 5e93268298d..00000000000 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache +++ /dev/null @@ -1,5 +0,0 @@ -module {{moduleName}} - module Swagger - VERSION = "{{gemVersion}}" - end -end diff --git a/modules/swagger-codegen/src/main/resources/ruby/version.mustache b/modules/swagger-codegen/src/main/resources/ruby/version.mustache new file mode 100644 index 00000000000..67cfc8ea325 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/version.mustache @@ -0,0 +1,3 @@ +module {{moduleName}} + VERSION = "{{gemVersion}}" +end From 948cdb3a75b6146d62c5af925013746724df222d Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 22 Jul 2015 15:37:29 +0800 Subject: [PATCH 03/17] Done with API client structure for Ruby client --- .../src/main/resources/ruby/api.mustache | 16 +- .../main/resources/ruby/api_client.mustache | 163 ++++++++++++------ .../main/resources/ruby/api_error.mustache | 24 +++ .../src/main/resources/ruby/request.mustache | 2 +- .../src/main/resources/ruby/response.mustache | 155 +++++++++++++++++ .../resources/ruby/swagger/api_error.mustache | 26 --- .../ruby/swagger/configuration.mustache | 101 ----------- .../resources/ruby/swagger/response.mustache | 156 ----------------- 8 files changed, 298 insertions(+), 345 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/ruby/api_error.mustache create mode 100644 modules/swagger-codegen/src/main/resources/ruby/response.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/ruby/swagger/api_error.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index bc62a114050..e1005a90159 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -18,8 +18,8 @@ module {{moduleName}} {{#allParams}}{{^required}} # @option opts [{{{dataType}}}] :{{paramName}} {{description}} {{/required}}{{/allParams}} # @return [{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}] def {{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {}) - if @client.debugging - @client.logger.debug "Calling API: {{classname}}#{{nickname}} ..." + if @api_client.debugging + @api_client.logger.debug "Calling API: {{classname}}#{{nickname}} ..." end {{#allParams}}{{#required}} # verify the required parameter '{{paramName}}' is set @@ -64,14 +64,14 @@ module {{moduleName}} {{/bodyParam}} auth_names = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}] - {{#returnType}}response = Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + {{#returnType}}response = Request.new(@api_client, :{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make result = response.deserialize('{{{returnType}}}') - if @client.debugging - @client.logger.debug "API called: {{classname}}#{{nickname}}. Result: #{result.inspect}" + if @api_client.debugging + @api_client.logger.debug "API called: {{classname}}#{{nickname}}. Result: #{result.inspect}" end - result{{/returnType}}{{^returnType}}Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - if @client.debugging - @client.logger.debug "API called: {{classname}}#{{nickname}}" + result{{/returnType}}{{^returnType}}Request.new(@api_client, :{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: {{classname}}#{{nickname}}" end nil{{/returnType}} end diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache index 8e295047dd9..e8fc5b9440a 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache @@ -3,75 +3,132 @@ require 'json' module {{moduleName}} class ApiClient + attr_accessor :scheme, :host, :base_path, :user_agent, :format, :auth_token, :inject_format, :force_ending_format + + # Defines the username used with HTTP basic authentication. + # + # @return [String] + attr_accessor :username + + # Defines the password used with HTTP basic authentication. + # + # @return [String] + attr_accessor :password + + # Defines API keys used with API Key authentications. + # + # @return [Hash] key: parameter name, value: parameter value (API key) + # + # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string) + # config.api_key['api_key'] = 'xxx' + attr_accessor :api_key + + # Defines API key prefixes used with API Key authentications. + # + # @return [Hash] key: parameter name, value: API key prefix + # + # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers) + # config.api_key_prefix['api_key'] = 'Token' + attr_accessor :api_key_prefix + + # Set this to false to skip verifying SSL certificate when calling API from https server. + # Default to true. + # + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + attr_accessor :verify_ssl + + # Set this to customize the certificate file to verify the peer. + # + # @return [String] the path to the certificate file + # + # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code: + # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 + attr_accessor :ssl_ca_cert + + # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response + # details will be logged with `logger.debug` (see the `logger` attribute). + # Default to false. + # + # @return [true, false] + attr_accessor :debugging + + # Defines the logger used for debugging. + # Default to `Rails.logger` (when in Rails) or logging to STDOUT. + # + # @return [#debug] attr_accessor :logger - # A Swagger configuration object. Must act like a hash and return sensible - # values for all Swagger configuration options. See Swagger::Configuration. - attr_accessor :configuration + # Defines the temporary folder to store downloaded files + # (for API endpoints that have file response). + # Default to use `Tempfile`. + # + # @return [String] + attr_accessor :temp_folder_path - attr_accessor :resources + # Defines the headers to be used in HTTP requests of all API calls by default. + # + # @return [Hash] + attr_accessor :default_headers - # Call this method to modify defaults in your initializers. + # Stores the HTTP response from the last API call using this API client. + attr_accessor :last_response + + # The constructor accepts a optional block to configure the API client. # # @example - # Swagger.configure do |config| - # config.api_key['api_key'] = '1234567890abcdef' # api key authentication - # config.username = 'wordlover' # http basic authentication - # config.password = 'i<3words' # http basic authentication - # config.format = 'json' # optional, defaults to 'json' + # {{moduleName}}::ApiClient.new do |client| + # client.api_key['api_key'] = 'your key' # api key authentication + # client.username = 'your username' # username for http basic authentication + # client.password = 'your password' # password for http basic authentication + # client.format = 'json' # optional, defaults to 'json' # end - # - def configure - yield(configuration) if block_given? + def initialize(&block) + @format = 'json' + @scheme = '{{scheme}}' + @host = '{{host}}' + @base_path = '{{contextPath}}' + @user_agent = "ruby-swagger-#{VERSION}" + @inject_format = false + @force_ending_format = false - self.logger = configuration.logger + @default_headers = { + 'Content-Type' => "application/#{@format.downcase}", + 'User-Agent' => @user_agent + } + + # keys for API key authentication (param-name => api-key) + @api_key = {} + @api_key_prefix = {} + + @verify_ssl = true + + @debugging = false + @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT) + + configure(&block) + end + + # Call this method to modify defaults in your initializers. + def configure + yield(self) if block_given? # remove :// from scheme - configuration.scheme.sub!(/:\/\//, '') + @scheme.sub!(/:\/\//, '') # remove http(s):// and anything after a slash - configuration.host.sub!(/https?:\/\//, '') - configuration.host = configuration.host.split('/').first + @host.sub!(/https?:\/\//, '') + @host = @host.split('/').first # Add leading and trailing slashes to base_path - configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/') - configuration.base_path = "" if configuration.base_path == "/" + @base_path = "/#{@base_path}".gsub(/\/+/, '/') + @base_path = "" if @base_path == "/" end - def authenticated? - !Swagger.configuration.auth_token.nil? - end - - def de_authenticate - Swagger.configuration.auth_token = nil - end - - def authenticate - return if Swagger.authenticated? - - if Swagger.configuration.username.nil? || Swagger.configuration.password.nil? - raise ApiError, "Username and password are required to authenticate." - end - - request = Swagger::Request.new( - :get, - "account/authenticate/{username}", - :params => { - :username => Swagger.configuration.username, - :password => Swagger.configuration.password - } - ) - - response_body = request.response.body - Swagger.configuration.auth_token = response_body['token'] - end - - def last_response - Thread.current[:swagger_last_response] - end - - def last_response=(response) - Thread.current[:swagger_last_response] = response + def user_agent=(user_agent) + @user_agent = user_agent + @default_headers['User-Agent'] = @user_agent end end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_error.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_error.mustache new file mode 100644 index 00000000000..f8b598dad71 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/api_error.mustache @@ -0,0 +1,24 @@ +module {{moduleName}} + class ApiError < StandardError + attr_reader :code, :response_headers, :response_body + + # Usage examples: + # ApiError.new + # ApiError.new("message") + # ApiError.new(:code => 500, :response_headers => {}, :response_body => "") + # ApiError.new(:code => 404, :message => "Not Found") + def initialize(arg = nil) + if arg.is_a? Hash + arg.each do |k, v| + if k.to_s == 'message' + super v + else + instance_variable_set "@#{k}", v + end + end + else + super arg + end + end + end +end diff --git a/modules/swagger-codegen/src/main/resources/ruby/request.mustache b/modules/swagger-codegen/src/main/resources/ruby/request.mustache index c3de5843483..6a7d2ac448e 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/request.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/request.mustache @@ -124,7 +124,7 @@ module {{moduleName}} end raw = Typhoeus::Request.new(self.url, request_options).run - @response = Response.new(raw) + @response = Response.new(@api_client, raw) if @api_client.debugging @api_client.logger.debug "HTTP response body ~BEGIN~\n#{@response.body}\n~END~\n" diff --git a/modules/swagger-codegen/src/main/resources/ruby/response.mustache b/modules/swagger-codegen/src/main/resources/ruby/response.mustache new file mode 100644 index 00000000000..d3119437232 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/response.mustache @@ -0,0 +1,155 @@ +require 'json' +require 'date' +require 'tempfile' + +module {{moduleName}} + class Response + attr_accessor :raw + + def initialize(api_client, raw) + @api_client = api_client + @raw = raw + end + + def code + raw.code + end + + def status_message + raw.status_message + end + + def body + raw.body + end + + def success? + raw.success? + end + + # Deserialize the raw response body to the given return type. + # + # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]" + def deserialize(return_type) + return nil if body.nil? || body.empty? + + # handle file downloading - save response body into a tmp file and return the File instance + return download_file if return_type == 'File' + + # ensuring a default content type + content_type = raw.headers['Content-Type'] || 'application/json' + + unless content_type.start_with?('application/json') + fail "Content-Type is not supported: #{content_type}" + end + + begin + data = JSON.parse("[#{body}]", :symbolize_names => true)[0] + rescue JSON::ParserError => e + if %w(String Date DateTime).include?(return_type) + data = body + else + raise e + end + end + + convert_to_type data, return_type + end + + # Convert data to the given return type. + def convert_to_type(data, return_type) + return nil if data.nil? + case return_type + 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 + when 'Date' + # parse date time (expecting ISO 8601 format) + Date.parse data + when 'Object' + # generic object, return directly + data + when /\AArray<(.+)>\z/ + # e.g. Array + sub_type = $1 + data.map {|item| convert_to_type(item, sub_type) } + when /\AHash\\z/ + # e.g. Hash + sub_type = $1 + {}.tap do |hash| + data.each {|k, v| hash[k] = convert_to_type(v, sub_type) } + end + else + # models, e.g. Pet + {{moduleName}}.const_get(return_type).new.tap do |model| + model.build_from_hash data + end + end + end + + # Save response body into a file in (the defined) temporary folder, using the filename + # from the "Content-Disposition" header if provided, otherwise a random filename. + # + # @see Configuration#temp_folder_path + # @return [File] the file downloaded + def download_file + tmp_file = Tempfile.new '', @api_client.temp_folder_path + content_disposition = raw.headers['Content-Disposition'] + if content_disposition + filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] + path = File.join File.dirname(tmp_file), filename + else + path = tmp_file.path + end + # close and delete temp file + tmp_file.close! + + File.open(path, 'w') { |file| file.write(raw.body) } + @api_client.logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards" + return File.new(path) + end + + # `headers_hash` is a Typhoeus-specific extension of Hash, + # so simplify it back into a regular old Hash. + def headers + h = {} + raw.headers_hash.each {|k,v| h[k] = v } + h + end + + # Extract the response format from the header hash + # e.g. {'Content-Type' => 'application/json'} + def format + headers['Content-Type'].split("/").last.downcase + end + + def json? + format == 'json' + end + + def xml? + format == 'xml' + end + + def pretty_body + return unless body + if format == 'json' + JSON.pretty_generate(JSON.parse(body)).gsub(/\n/, '
') + else + body + end + end + + def pretty_headers + JSON.pretty_generate(headers).gsub(/\n/, '
') + end + end +end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/api_error.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/api_error.mustache deleted file mode 100644 index 552161238a0..00000000000 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/api_error.mustache +++ /dev/null @@ -1,26 +0,0 @@ -module {{moduleName}} - module Swagger - class ApiError < StandardError - attr_reader :code, :response_headers, :response_body - - # Usage examples: - # ApiError.new - # ApiError.new("message") - # ApiError.new(:code => 500, :response_headers => {}, :response_body => "") - # ApiError.new(:code => 404, :message => "Not Found") - def initialize(arg = nil) - if arg.is_a? Hash - arg.each do |k, v| - if k.to_s == 'message' - super v - else - instance_variable_set "@#{k}", v - end - end - else - super arg - end - end - end - end -end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache deleted file mode 100644 index 1279a454e71..00000000000 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache +++ /dev/null @@ -1,101 +0,0 @@ -require 'logger' - -module {{moduleName}} - module Swagger - class Configuration - attr_accessor :scheme, :host, :base_path, :user_agent, :format, :auth_token, :inject_format, :force_ending_format - - # Defines the username used with HTTP basic authentication. - # - # @return [String] - attr_accessor :username - - # Defines the password used with HTTP basic authentication. - # - # @return [String] - attr_accessor :password - - # Defines API keys used with API Key authentications. - # - # @return [Hash] key: parameter name, value: parameter value (API key) - # - # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string) - # config.api_key['api_key'] = 'xxx' - attr_accessor :api_key - - # Defines API key prefixes used with API Key authentications. - # - # @return [Hash] key: parameter name, value: API key prefix - # - # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers) - # config.api_key_prefix['api_key'] = 'Token' - attr_accessor :api_key_prefix - - # Set this to false to skip verifying SSL certificate when calling API from https server. - # Default to true. - # - # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. - # - # @return [true, false] - attr_accessor :verify_ssl - - # Set this to customize the certificate file to verify the peer. - # - # @return [String] the path to the certificate file - # - # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code: - # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 - attr_accessor :ssl_ca_cert - - # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response - # details will be logged with `logger.debug` (see the `logger` attribute). - # Default to false. - # - # @return [true, false] - attr_accessor :debug - - # Defines the logger used for debugging. - # Default to `Rails.logger` (when in Rails) or logging to STDOUT. - # - # @return [#debug] - attr_accessor :logger - - # Defines the temporary folder to store downloaded files - # (for API endpoints that have file response). - # Default to use `Tempfile`. - # - # @return [String] - attr_accessor :temp_folder_path - - # Defines the headers to be used in HTTP requests of all API calls by default. - # - # @return [Hash] - attr_accessor :default_headers - - # Defaults go in here.. - def initialize - @format = 'json' - @scheme = '{{scheme}}' - @host = '{{host}}' - @base_path = '{{contextPath}}' - @user_agent = "ruby-swagger-#{Swagger::VERSION}" - @inject_format = false - @force_ending_format = false - - @default_headers = { - 'Content-Type' => "application/#{@format.downcase}", - 'User-Agent' => @user_agent - } - - # keys for API key authentication (param-name => api-key) - @api_key = {} - @api_key_prefix = {} - - @verify_ssl = true - - @debug = false - @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT) - end - end - end -end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache deleted file mode 100644 index 5f55fd68690..00000000000 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache +++ /dev/null @@ -1,156 +0,0 @@ -module {{moduleName}} - module Swagger - class Response - require 'json' - require 'date' - require 'tempfile' - - attr_accessor :raw - - def initialize(raw) - self.raw = raw - end - - def code - raw.code - end - - def status_message - raw.status_message - end - - def body - raw.body - end - - def success? - raw.success? - end - - # Deserialize the raw response body to the given return type. - # - # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]" - def deserialize(return_type) - return nil if body.nil? || body.empty? - - # handle file downloading - save response body into a tmp file and return the File instance - return download_file if return_type == 'File' - - # ensuring a default content type - content_type = raw.headers['Content-Type'] || 'application/json' - - unless content_type.start_with?('application/json') - fail "Content-Type is not supported: #{content_type}" - end - - begin - data = JSON.parse("[#{body}]", :symbolize_names => true)[0] - rescue JSON::ParserError => e - if %w(String Date DateTime).include?(return_type) - data = body - else - raise e - end - end - - convert_to_type data, return_type - end - - # Convert data to the given return type. - def convert_to_type(data, return_type) - return nil if data.nil? - case return_type - 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 - when 'Date' - # parse date time (expecting ISO 8601 format) - Date.parse data - when 'Object' - # generic object, return directly - data - when /\AArray<(.+)>\z/ - # e.g. Array - sub_type = $1 - data.map {|item| convert_to_type(item, sub_type) } - when /\AHash\\z/ - # e.g. Hash - sub_type = $1 - {}.tap do |hash| - data.each {|k, v| hash[k] = convert_to_type(v, sub_type) } - end - else - # models, e.g. Pet - {{moduleName}}.const_get(return_type).new.tap do |model| - model.build_from_hash data - end - end - end - - # Save response body into a file in (the defined) temporary folder, using the filename - # from the "Content-Disposition" header if provided, otherwise a random filename. - # - # @see Configuration#temp_folder_path - # @return [File] the file downloaded - def download_file - tmp_file = Tempfile.new '', Swagger.configuration.temp_folder_path - content_disposition = raw.headers['Content-Disposition'] - if content_disposition - filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] - path = File.join File.dirname(tmp_file), filename - else - path = tmp_file.path - end - # close and delete temp file - tmp_file.close! - - File.open(path, 'w') { |file| file.write(raw.body) } - Swagger.logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards" - return File.new(path) - end - - # `headers_hash` is a Typhoeus-specific extension of Hash, - # so simplify it back into a regular old Hash. - def headers - h = {} - raw.headers_hash.each {|k,v| h[k] = v } - h - end - - # Extract the response format from the header hash - # e.g. {'Content-Type' => 'application/json'} - def format - headers['Content-Type'].split("/").last.downcase - end - - def json? - format == 'json' - end - - def xml? - format == 'xml' - end - - def pretty_body - return unless body - if format == 'json' - JSON.pretty_generate(JSON.parse(body)).gsub(/\n/, '
') - else - body - end - end - - def pretty_headers - JSON.pretty_generate(headers).gsub(/\n/, '
') - end - end - end -end From 609d915541ac99dd52330e13e04f3347b2811bf8 Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 22 Jul 2015 15:39:48 +0800 Subject: [PATCH 04/17] Rebuild Ruby petstore sample --- samples/client/petstore/ruby/README.md | 21 +- samples/client/petstore/ruby/lib/petstore.rb | 16 +- .../petstore/ruby/lib/petstore/api/pet_api.rb | 138 ++++++------ .../ruby/lib/petstore/api/store_api.rb | 72 +++--- .../ruby/lib/petstore/api/user_api.rb | 142 ++++++------ .../petstore/ruby/lib/petstore/api_client.rb | 134 +++++++++++ .../petstore/ruby/lib/petstore/api_error.rb | 24 ++ .../petstore/ruby/lib/petstore/request.rb | 207 +++++++++++++++++ .../petstore/ruby/lib/petstore/response.rb | 155 +++++++++++++ .../petstore/ruby/lib/petstore/swagger.rb | 76 ------- .../ruby/lib/petstore/swagger/api_error.rb | 26 --- .../lib/petstore/swagger/configuration.rb | 101 --------- .../ruby/lib/petstore/swagger/request.rb | 213 ------------------ .../ruby/lib/petstore/swagger/response.rb | 156 ------------- .../ruby/lib/petstore/swagger/version.rb | 5 - .../petstore/ruby/lib/petstore/version.rb | 3 + samples/client/petstore/ruby/petstore.gemspec | 4 +- 17 files changed, 725 insertions(+), 768 deletions(-) create mode 100644 samples/client/petstore/ruby/lib/petstore/api_client.rb create mode 100644 samples/client/petstore/ruby/lib/petstore/api_error.rb create mode 100644 samples/client/petstore/ruby/lib/petstore/request.rb create mode 100644 samples/client/petstore/ruby/lib/petstore/response.rb delete mode 100644 samples/client/petstore/ruby/lib/petstore/swagger.rb delete mode 100644 samples/client/petstore/ruby/lib/petstore/swagger/api_error.rb delete mode 100644 samples/client/petstore/ruby/lib/petstore/swagger/configuration.rb delete mode 100644 samples/client/petstore/ruby/lib/petstore/swagger/request.rb delete mode 100644 samples/client/petstore/ruby/lib/petstore/swagger/response.rb delete mode 100644 samples/client/petstore/ruby/lib/petstore/swagger/version.rb create mode 100644 samples/client/petstore/ruby/lib/petstore/version.rb diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index c98d79e5a89..b251d14faf7 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -37,23 +37,20 @@ You can also use the client directly like this: ruby -Ilib script.rb ``` -## Configuration +## Getting Started ```ruby require 'petstore' -Petstore::Swagger.configure do |config| - config.api_key['api_key'] = 'special-key' - config.host = 'petstore.swagger.io' - config.base_path = '/v2' - # enable debugging (default is false) - config.debug = true +api_client = Petstore::ApiClient.new do |client| + client.api_key['api_key'] = 'special-key' + client.host = 'petstore.swagger.io' + client.base_path = '/v2' + # enable debugging (default is disabled) + client.debugging = true end -``` -## Getting Started - -```ruby -pet = Petstore::PetApi.get_pet_by_id(5) +pet_api = Petstore::PetApi.new(api_client) +pet = pet_api.get_pet_by_id(5) puts pet.to_body ``` diff --git a/samples/client/petstore/ruby/lib/petstore.rb b/samples/client/petstore/ruby/lib/petstore.rb index a3f555c1765..f77710df1ea 100644 --- a/samples/client/petstore/ruby/lib/petstore.rb +++ b/samples/client/petstore/ruby/lib/petstore.rb @@ -1,10 +1,9 @@ -# Swagger common files -require 'petstore/swagger' -require 'petstore/swagger/configuration' -require 'petstore/swagger/api_error' -require 'petstore/swagger/request' -require 'petstore/swagger/response' -require 'petstore/swagger/version' +# Common files +require 'petstore/api_client' +require 'petstore/api_error' +require 'petstore/request' +require 'petstore/response' +require 'petstore/version' # Models require 'petstore/models/base_object' @@ -20,7 +19,4 @@ require 'petstore/api/pet_api' require 'petstore/api/store_api' module Petstore - # Initialize the default configuration - Swagger.configuration = Swagger::Configuration.new - Swagger.configure { |config| } end diff --git a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb index 51c3cec7fde..b50b56e6343 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb @@ -2,15 +2,21 @@ require "uri" module Petstore class PetApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.new) + @api_client = api_client + end + # Update an existing pet # # @param [Hash] opts the optional parameters # @option opts [Pet] :body Pet object that needs to be added to the store # @return [nil] - def self.update_pet(opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: PetApi#update_pet ..." + def update_pet(opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: PetApi#update_pet ..." end # resource path @@ -24,23 +30,23 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = ['application/json', 'application/xml'] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Swagger::Request.object_to_http_body(opts[:'body']) + post_body = Request.object_to_http_body(opts[:'body']) auth_names = ['petstore_auth'] - Swagger::Request.new(:PUT, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - if Swagger.configuration.debug - Swagger.logger.debug "API called: PetApi#update_pet" + Request.new(@api_client, :PUT, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: PetApi#update_pet" end nil end @@ -50,9 +56,9 @@ module Petstore # @param [Hash] opts the optional parameters # @option opts [Pet] :body Pet object that needs to be added to the store # @return [nil] - def self.add_pet(opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: PetApi#add_pet ..." + def add_pet(opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: PetApi#add_pet ..." end # resource path @@ -66,23 +72,23 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = ['application/json', 'application/xml'] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Swagger::Request.object_to_http_body(opts[:'body']) + post_body = Request.object_to_http_body(opts[:'body']) auth_names = ['petstore_auth'] - Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - if Swagger.configuration.debug - Swagger.logger.debug "API called: PetApi#add_pet" + Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: PetApi#add_pet" end nil end @@ -92,9 +98,9 @@ module Petstore # @param [Hash] opts the optional parameters # @option opts [Array] :status Status values that need to be considered for filter # @return [Array] - def self.find_pets_by_status(opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: PetApi#find_pets_by_status ..." + def find_pets_by_status(opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: PetApi#find_pets_by_status ..." end # resource path @@ -109,11 +115,11 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -123,10 +129,10 @@ module Petstore auth_names = ['petstore_auth'] - response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make result = response.deserialize('Array') - if Swagger.configuration.debug - Swagger.logger.debug "API called: PetApi#find_pets_by_status. Result: #{result.inspect}" + if @api_client.debugging + @api_client.logger.debug "API called: PetApi#find_pets_by_status. Result: #{result.inspect}" end result end @@ -136,9 +142,9 @@ module Petstore # @param [Hash] opts the optional parameters # @option opts [Array] :tags Tags to filter by # @return [Array] - def self.find_pets_by_tags(opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: PetApi#find_pets_by_tags ..." + def find_pets_by_tags(opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: PetApi#find_pets_by_tags ..." end # resource path @@ -153,11 +159,11 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -167,10 +173,10 @@ module Petstore auth_names = ['petstore_auth'] - response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make result = response.deserialize('Array') - if Swagger.configuration.debug - Swagger.logger.debug "API called: PetApi#find_pets_by_tags. Result: #{result.inspect}" + if @api_client.debugging + @api_client.logger.debug "API called: PetApi#find_pets_by_tags. Result: #{result.inspect}" end result end @@ -180,9 +186,9 @@ module Petstore # @param pet_id ID of pet that needs to be fetched # @param [Hash] opts the optional parameters # @return [Pet] - def self.get_pet_by_id(pet_id, opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: PetApi#get_pet_by_id ..." + def get_pet_by_id(pet_id, opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: PetApi#get_pet_by_id ..." end # verify the required parameter 'pet_id' is set @@ -199,11 +205,11 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -213,10 +219,10 @@ module Petstore auth_names = ['api_key', 'petstore_auth'] - response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make result = response.deserialize('Pet') - if Swagger.configuration.debug - Swagger.logger.debug "API called: PetApi#get_pet_by_id. Result: #{result.inspect}" + if @api_client.debugging + @api_client.logger.debug "API called: PetApi#get_pet_by_id. Result: #{result.inspect}" end result end @@ -228,9 +234,9 @@ module Petstore # @option opts [String] :name Updated name of the pet # @option opts [String] :status Updated status of the pet # @return [nil] - def self.update_pet_with_form(pet_id, opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: PetApi#update_pet_with_form ..." + def update_pet_with_form(pet_id, opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: PetApi#update_pet_with_form ..." end # verify the required parameter 'pet_id' is set @@ -247,11 +253,11 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = ['application/x-www-form-urlencoded'] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -263,9 +269,9 @@ module Petstore auth_names = ['petstore_auth'] - Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - if Swagger.configuration.debug - Swagger.logger.debug "API called: PetApi#update_pet_with_form" + Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: PetApi#update_pet_with_form" end nil end @@ -276,9 +282,9 @@ module Petstore # @param [Hash] opts the optional parameters # @option opts [String] :api_key # @return [nil] - def self.delete_pet(pet_id, opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: PetApi#delete_pet ..." + def delete_pet(pet_id, opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: PetApi#delete_pet ..." end # verify the required parameter 'pet_id' is set @@ -295,11 +301,11 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) header_params[:'api_key'] = opts[:'api_key'] if opts[:'api_key'] # form parameters @@ -310,9 +316,9 @@ module Petstore auth_names = ['petstore_auth'] - Swagger::Request.new(:DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - if Swagger.configuration.debug - Swagger.logger.debug "API called: PetApi#delete_pet" + Request.new(@api_client, :DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: PetApi#delete_pet" end nil end @@ -324,9 +330,9 @@ module Petstore # @option opts [String] :additional_metadata Additional data to pass to server # @option opts [File] :file file to upload # @return [nil] - def self.upload_file(pet_id, opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: PetApi#upload_file ..." + def upload_file(pet_id, opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: PetApi#upload_file ..." end # verify the required parameter 'pet_id' is set @@ -343,11 +349,11 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = ['multipart/form-data'] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -359,9 +365,9 @@ module Petstore auth_names = ['petstore_auth'] - Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - if Swagger.configuration.debug - Swagger.logger.debug "API called: PetApi#upload_file" + Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: PetApi#upload_file" end nil end diff --git a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb index 78328f4b832..3462cd8f7de 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb @@ -2,14 +2,20 @@ require "uri" module Petstore class StoreApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.new) + @api_client = api_client + end + # Returns pet inventories by status # Returns a map of status codes to quantities # @param [Hash] opts the optional parameters # @return [Hash] - def self.get_inventory(opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: StoreApi#get_inventory ..." + def get_inventory(opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: StoreApi#get_inventory ..." end # resource path @@ -23,11 +29,11 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -37,10 +43,10 @@ module Petstore auth_names = ['api_key'] - response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make result = response.deserialize('Hash') - if Swagger.configuration.debug - Swagger.logger.debug "API called: StoreApi#get_inventory. Result: #{result.inspect}" + if @api_client.debugging + @api_client.logger.debug "API called: StoreApi#get_inventory. Result: #{result.inspect}" end result end @@ -50,9 +56,9 @@ module Petstore # @param [Hash] opts the optional parameters # @option opts [Order] :body order placed for purchasing the pet # @return [Order] - def self.place_order(opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: StoreApi#place_order ..." + def place_order(opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: StoreApi#place_order ..." end # resource path @@ -66,24 +72,24 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Swagger::Request.object_to_http_body(opts[:'body']) + post_body = Request.object_to_http_body(opts[:'body']) auth_names = [] - response = Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + response = Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make result = response.deserialize('Order') - if Swagger.configuration.debug - Swagger.logger.debug "API called: StoreApi#place_order. Result: #{result.inspect}" + if @api_client.debugging + @api_client.logger.debug "API called: StoreApi#place_order. Result: #{result.inspect}" end result end @@ -93,9 +99,9 @@ module Petstore # @param order_id ID of pet that needs to be fetched # @param [Hash] opts the optional parameters # @return [Order] - def self.get_order_by_id(order_id, opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: StoreApi#get_order_by_id ..." + def get_order_by_id(order_id, opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: StoreApi#get_order_by_id ..." end # verify the required parameter 'order_id' is set @@ -112,11 +118,11 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -126,10 +132,10 @@ module Petstore auth_names = [] - response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make result = response.deserialize('Order') - if Swagger.configuration.debug - Swagger.logger.debug "API called: StoreApi#get_order_by_id. Result: #{result.inspect}" + if @api_client.debugging + @api_client.logger.debug "API called: StoreApi#get_order_by_id. Result: #{result.inspect}" end result end @@ -139,9 +145,9 @@ module Petstore # @param order_id ID of the order that needs to be deleted # @param [Hash] opts the optional parameters # @return [nil] - def self.delete_order(order_id, opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: StoreApi#delete_order ..." + def delete_order(order_id, opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: StoreApi#delete_order ..." end # verify the required parameter 'order_id' is set @@ -158,11 +164,11 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -172,9 +178,9 @@ module Petstore auth_names = [] - Swagger::Request.new(:DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - if Swagger.configuration.debug - Swagger.logger.debug "API called: StoreApi#delete_order" + Request.new(@api_client, :DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: StoreApi#delete_order" end nil end diff --git a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb index 532a9ffa5bf..5664f735f01 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb @@ -2,15 +2,21 @@ require "uri" module Petstore class UserApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.new) + @api_client = api_client + end + # Create user # This can only be done by the logged in user. # @param [Hash] opts the optional parameters # @option opts [User] :body Created user object # @return [nil] - def self.create_user(opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: UserApi#create_user ..." + def create_user(opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: UserApi#create_user ..." end # resource path @@ -24,23 +30,23 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Swagger::Request.object_to_http_body(opts[:'body']) + post_body = Request.object_to_http_body(opts[:'body']) auth_names = [] - Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - if Swagger.configuration.debug - Swagger.logger.debug "API called: UserApi#create_user" + Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: UserApi#create_user" end nil end @@ -50,9 +56,9 @@ module Petstore # @param [Hash] opts the optional parameters # @option opts [Array] :body List of user object # @return [nil] - def self.create_users_with_array_input(opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: UserApi#create_users_with_array_input ..." + def create_users_with_array_input(opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: UserApi#create_users_with_array_input ..." end # resource path @@ -66,23 +72,23 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Swagger::Request.object_to_http_body(opts[:'body']) + post_body = Request.object_to_http_body(opts[:'body']) auth_names = [] - Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - if Swagger.configuration.debug - Swagger.logger.debug "API called: UserApi#create_users_with_array_input" + Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: UserApi#create_users_with_array_input" end nil end @@ -92,9 +98,9 @@ module Petstore # @param [Hash] opts the optional parameters # @option opts [Array] :body List of user object # @return [nil] - def self.create_users_with_list_input(opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: UserApi#create_users_with_list_input ..." + def create_users_with_list_input(opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: UserApi#create_users_with_list_input ..." end # resource path @@ -108,23 +114,23 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Swagger::Request.object_to_http_body(opts[:'body']) + post_body = Request.object_to_http_body(opts[:'body']) auth_names = [] - Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - if Swagger.configuration.debug - Swagger.logger.debug "API called: UserApi#create_users_with_list_input" + Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: UserApi#create_users_with_list_input" end nil end @@ -135,9 +141,9 @@ module Petstore # @option opts [String] :username The user name for login # @option opts [String] :password The password for login in clear text # @return [String] - def self.login_user(opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: UserApi#login_user ..." + def login_user(opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: UserApi#login_user ..." end # resource path @@ -153,11 +159,11 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -167,10 +173,10 @@ module Petstore auth_names = [] - response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make result = response.deserialize('String') - if Swagger.configuration.debug - Swagger.logger.debug "API called: UserApi#login_user. Result: #{result.inspect}" + if @api_client.debugging + @api_client.logger.debug "API called: UserApi#login_user. Result: #{result.inspect}" end result end @@ -179,9 +185,9 @@ module Petstore # # @param [Hash] opts the optional parameters # @return [nil] - def self.logout_user(opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: UserApi#logout_user ..." + def logout_user(opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: UserApi#logout_user ..." end # resource path @@ -195,11 +201,11 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -209,9 +215,9 @@ module Petstore auth_names = [] - Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - if Swagger.configuration.debug - Swagger.logger.debug "API called: UserApi#logout_user" + Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: UserApi#logout_user" end nil end @@ -221,9 +227,9 @@ module Petstore # @param username The name that needs to be fetched. Use user1 for testing. # @param [Hash] opts the optional parameters # @return [User] - def self.get_user_by_name(username, opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: UserApi#get_user_by_name ..." + def get_user_by_name(username, opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: UserApi#get_user_by_name ..." end # verify the required parameter 'username' is set @@ -240,11 +246,11 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -254,10 +260,10 @@ module Petstore auth_names = [] - response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make result = response.deserialize('User') - if Swagger.configuration.debug - Swagger.logger.debug "API called: UserApi#get_user_by_name. Result: #{result.inspect}" + if @api_client.debugging + @api_client.logger.debug "API called: UserApi#get_user_by_name. Result: #{result.inspect}" end result end @@ -268,9 +274,9 @@ module Petstore # @param [Hash] opts the optional parameters # @option opts [User] :body Updated user object # @return [nil] - def self.update_user(username, opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: UserApi#update_user ..." + def update_user(username, opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: UserApi#update_user ..." end # verify the required parameter 'username' is set @@ -287,23 +293,23 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Swagger::Request.object_to_http_body(opts[:'body']) + post_body = Request.object_to_http_body(opts[:'body']) auth_names = [] - Swagger::Request.new(:PUT, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - if Swagger.configuration.debug - Swagger.logger.debug "API called: UserApi#update_user" + Request.new(@api_client, :PUT, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: UserApi#update_user" end nil end @@ -313,9 +319,9 @@ module Petstore # @param username The name that needs to be deleted # @param [Hash] opts the optional parameters # @return [nil] - def self.delete_user(username, opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: UserApi#delete_user ..." + def delete_user(username, opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: UserApi#delete_user ..." end # verify the required parameter 'username' is set @@ -332,11 +338,11 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -346,9 +352,9 @@ module Petstore auth_names = [] - Swagger::Request.new(:DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - if Swagger.configuration.debug - Swagger.logger.debug "API called: UserApi#delete_user" + Request.new(@api_client, :DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: UserApi#delete_user" end nil end diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb new file mode 100644 index 00000000000..569003fa133 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -0,0 +1,134 @@ +require 'logger' +require 'json' + +module Petstore + class ApiClient + attr_accessor :scheme, :host, :base_path, :user_agent, :format, :auth_token, :inject_format, :force_ending_format + + # Defines the username used with HTTP basic authentication. + # + # @return [String] + attr_accessor :username + + # Defines the password used with HTTP basic authentication. + # + # @return [String] + attr_accessor :password + + # Defines API keys used with API Key authentications. + # + # @return [Hash] key: parameter name, value: parameter value (API key) + # + # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string) + # config.api_key['api_key'] = 'xxx' + attr_accessor :api_key + + # Defines API key prefixes used with API Key authentications. + # + # @return [Hash] key: parameter name, value: API key prefix + # + # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers) + # config.api_key_prefix['api_key'] = 'Token' + attr_accessor :api_key_prefix + + # Set this to false to skip verifying SSL certificate when calling API from https server. + # Default to true. + # + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + attr_accessor :verify_ssl + + # Set this to customize the certificate file to verify the peer. + # + # @return [String] the path to the certificate file + # + # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code: + # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 + attr_accessor :ssl_ca_cert + + # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response + # details will be logged with `logger.debug` (see the `logger` attribute). + # Default to false. + # + # @return [true, false] + attr_accessor :debugging + + # Defines the logger used for debugging. + # Default to `Rails.logger` (when in Rails) or logging to STDOUT. + # + # @return [#debug] + attr_accessor :logger + + # Defines the temporary folder to store downloaded files + # (for API endpoints that have file response). + # Default to use `Tempfile`. + # + # @return [String] + attr_accessor :temp_folder_path + + # Defines the headers to be used in HTTP requests of all API calls by default. + # + # @return [Hash] + attr_accessor :default_headers + + # Stores the HTTP response from the last API call using this API client. + attr_accessor :last_response + + # The constructor accepts a optional block to configure the API client. + # + # @example + # Petstore::ApiClient.new do |client| + # client.api_key['api_key'] = 'your key' # api key authentication + # client.username = 'your username' # username for http basic authentication + # client.password = 'your password' # password for http basic authentication + # client.format = 'json' # optional, defaults to 'json' + # end + def initialize(&block) + @format = 'json' + @scheme = 'http' + @host = 'petstore.swagger.io' + @base_path = '/v2' + @user_agent = "ruby-swagger-#{VERSION}" + @inject_format = false + @force_ending_format = false + + @default_headers = { + 'Content-Type' => "application/#{@format.downcase}", + 'User-Agent' => @user_agent + } + + # keys for API key authentication (param-name => api-key) + @api_key = {} + @api_key_prefix = {} + + @verify_ssl = true + + @debugging = false + @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT) + + configure(&block) + end + + # Call this method to modify defaults in your initializers. + def configure + yield(self) if block_given? + + # remove :// from scheme + @scheme.sub!(/:\/\//, '') + + # remove http(s):// and anything after a slash + @host.sub!(/https?:\/\//, '') + @host = @host.split('/').first + + # Add leading and trailing slashes to base_path + @base_path = "/#{@base_path}".gsub(/\/+/, '/') + @base_path = "" if @base_path == "/" + end + + def user_agent=(user_agent) + @user_agent = user_agent + @default_headers['User-Agent'] = @user_agent + end + end +end diff --git a/samples/client/petstore/ruby/lib/petstore/api_error.rb b/samples/client/petstore/ruby/lib/petstore/api_error.rb new file mode 100644 index 00000000000..e1b6b3acfd6 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/api_error.rb @@ -0,0 +1,24 @@ +module Petstore + class ApiError < StandardError + attr_reader :code, :response_headers, :response_body + + # Usage examples: + # ApiError.new + # ApiError.new("message") + # ApiError.new(:code => 500, :response_headers => {}, :response_body => "") + # ApiError.new(:code => 404, :message => "Not Found") + def initialize(arg = nil) + if arg.is_a? Hash + arg.each do |k, v| + if k.to_s == 'message' + super v + else + instance_variable_set "@#{k}", v + end + end + else + super arg + end + end + end +end diff --git a/samples/client/petstore/ruby/lib/petstore/request.rb b/samples/client/petstore/ruby/lib/petstore/request.rb new file mode 100644 index 00000000000..af884537ff8 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/request.rb @@ -0,0 +1,207 @@ +require 'uri' +require 'typhoeus' + +module Petstore + class Request + attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params, :auth_names, :response + + # All requests must have an HTTP method and a path + # Optionals parameters are :params, :headers, :body, :format, :host + def initialize(api_client, http_method, path, attributes = {}) + @api_client = api_client + + @http_method = http_method.to_sym.downcase + @path = path + + attributes.each { |name, value| send "#{name}=", value } + + @format ||= @api_client.format + @params ||= {} + + # Apply default headers + @headers = @api_client.default_headers.merge(@headers || {}) + + update_params_for_auth! + + end + + + # Update hearder and query params based on authentication settings. + def update_params_for_auth! + (@auth_names || []).each do |auth_name| + case auth_name + when 'api_key' + @headers ||= {} + @headers['api_key'] = get_api_key_with_prefix('api_key') + when 'petstore_auth' + # TODO: support oauth + + end + end + end + + + # Get API key (with prefix if set). + # @param [String] param_name the parameter name of API key auth + def get_api_key_with_prefix(param_name) + if @api_client.api_key_prefix[param_name] + "#{@api_client.api_key_prefix[param_name]} #{@api_client.api_key[param_name]}" + else + @api_client.api_key[param_name] + end + end + + # Construct the request URL. + def url(options = {}) + _path = self.interpreted_path + _path = "/#{_path}" unless _path.start_with?('/') + "#{@api_client.scheme}://#{@api_client.host}#{_path}" + end + + # Iterate over the params hash, injecting any path values into the path string + # e.g. /word.{format}/{word}/entries => /word.json/cat/entries + def interpreted_path + p = self.path.dup + + # Stick a .{format} placeholder into the path if there isn't + # one already or an actual format like json or xml + # e.g. /words/blah => /words.{format}/blah + if @api_client.inject_format + unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } + p = p.sub(/^(\/?\w+)/, "\\1.#{format}") + end + end + + # Stick a .{format} placeholder on the end of the path if there isn't + # one already or an actual format like json or xml + # e.g. /words/blah => /words/blah.{format} + if @api_client.force_ending_format + unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } + p = "#{p}.#{format}" + end + end + + p = p.sub("{format}", self.format.to_s) + + URI.encode [@api_client.base_path, p].join("/").gsub(/\/+/, '/') + end + + # If body is an object, JSONify it before making the actual request. + # For form parameters, remove empty value + def outgoing_body + # http form + if headers['Content-Type'] == 'application/x-www-form-urlencoded' + data = form_params.dup + data.each do |key, value| + data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter + end + elsif @body # http body is JSON + data = @body.is_a?(String) ? @body : @body.to_json + else + data = nil + end + + if @api_client.debugging + @api_client.logger.debug "HTTP request body param ~BEGIN~\n#{data}\n~END~\n" + end + + data + end + + def make + request_options = { + :method => self.http_method, + :headers => self.headers, + :params => self.params, + :ssl_verifypeer => @api_client.verify_ssl, + :cainfo => @api_client.ssl_ca_cert, + :verbose => @api_client.debugging + } + + if [:post, :patch, :put, :delete].include?(self.http_method) + request_options.update :body => self.outgoing_body + end + + raw = Typhoeus::Request.new(self.url, request_options).run + @response = Response.new(@api_client, raw) + + if @api_client.debugging + @api_client.logger.debug "HTTP response body ~BEGIN~\n#{@response.body}\n~END~\n" + end + + # record as last response + @api_client.last_response = @response + + unless @response.success? + fail ApiError.new(:code => @response.code, + :response_headers => @response.headers, + :response_body => @response.body), + @response.status_message + end + + @response + end + + def response_code_pretty + return unless @response + @response.code.to_s + end + + def response_headers_pretty + return unless @response + # JSON.pretty_generate(@response.headers).gsub(/\n/, '
') # <- This was for RestClient + @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus + end + + # return 'Accept' based on an array of accept provided + # @param [Array] header_accept_array Array fo 'Accept' + # @return String Accept (e.g. application/json) + def self.select_header_accept header_accept_array + if header_accept_array.empty? + return + elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 } + 'application/json' # look for json data by default + else + header_accept_array.join(',') + end + end + + # return the content type based on an array of content-type provided + # @param [Array] content_type_array Array fo content-type + # @return String Content-Type (e.g. application/json) + def self.select_header_content_type content_type_array + if content_type_array.empty? + 'application/json' # use application/json by default + elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 } + 'application/json' # use application/json if it's included + else + content_type_array[0]; # otherwise, use the first one + end + end + + # static method to convert object (array, hash, object, etc) to JSON string + # @param model object to be converted into JSON string + # @return string JSON string representation of the object + def self.object_to_http_body model + return if model.nil? + _body = nil + if model.is_a?(Array) + _body = model.map{|m| object_to_hash(m) } + else + _body = object_to_hash(model) + end + _body.to_json + end + + # static method to convert object(non-array) to hash + # @param obj object to be converted into JSON string + # @return string JSON string representation of the object + def self.object_to_hash obj + if obj.respond_to?(:to_hash) + obj.to_hash + else + obj + end + end + end +end diff --git a/samples/client/petstore/ruby/lib/petstore/response.rb b/samples/client/petstore/ruby/lib/petstore/response.rb new file mode 100644 index 00000000000..e54e13ac951 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/response.rb @@ -0,0 +1,155 @@ +require 'json' +require 'date' +require 'tempfile' + +module Petstore + class Response + attr_accessor :raw + + def initialize(api_client, raw) + @api_client = api_client + @raw = raw + end + + def code + raw.code + end + + def status_message + raw.status_message + end + + def body + raw.body + end + + def success? + raw.success? + end + + # Deserialize the raw response body to the given return type. + # + # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]" + def deserialize(return_type) + return nil if body.nil? || body.empty? + + # handle file downloading - save response body into a tmp file and return the File instance + return download_file if return_type == 'File' + + # ensuring a default content type + content_type = raw.headers['Content-Type'] || 'application/json' + + unless content_type.start_with?('application/json') + fail "Content-Type is not supported: #{content_type}" + end + + begin + data = JSON.parse("[#{body}]", :symbolize_names => true)[0] + rescue JSON::ParserError => e + if %w(String Date DateTime).include?(return_type) + data = body + else + raise e + end + end + + convert_to_type data, return_type + end + + # Convert data to the given return type. + def convert_to_type(data, return_type) + return nil if data.nil? + case return_type + 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 + when 'Date' + # parse date time (expecting ISO 8601 format) + Date.parse data + when 'Object' + # generic object, return directly + data + when /\AArray<(.+)>\z/ + # e.g. Array + sub_type = $1 + data.map {|item| convert_to_type(item, sub_type) } + when /\AHash\\z/ + # e.g. Hash + sub_type = $1 + {}.tap do |hash| + data.each {|k, v| hash[k] = convert_to_type(v, sub_type) } + end + else + # models, e.g. Pet + Petstore.const_get(return_type).new.tap do |model| + model.build_from_hash data + end + end + end + + # Save response body into a file in (the defined) temporary folder, using the filename + # from the "Content-Disposition" header if provided, otherwise a random filename. + # + # @see Configuration#temp_folder_path + # @return [File] the file downloaded + def download_file + tmp_file = Tempfile.new '', @api_client.temp_folder_path + content_disposition = raw.headers['Content-Disposition'] + if content_disposition + filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] + path = File.join File.dirname(tmp_file), filename + else + path = tmp_file.path + end + # close and delete temp file + tmp_file.close! + + File.open(path, 'w') { |file| file.write(raw.body) } + @api_client.logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards" + return File.new(path) + end + + # `headers_hash` is a Typhoeus-specific extension of Hash, + # so simplify it back into a regular old Hash. + def headers + h = {} + raw.headers_hash.each {|k,v| h[k] = v } + h + end + + # Extract the response format from the header hash + # e.g. {'Content-Type' => 'application/json'} + def format + headers['Content-Type'].split("/").last.downcase + end + + def json? + format == 'json' + end + + def xml? + format == 'xml' + end + + def pretty_body + return unless body + if format == 'json' + JSON.pretty_generate(JSON.parse(body)).gsub(/\n/, '
') + else + body + end + end + + def pretty_headers + JSON.pretty_generate(headers).gsub(/\n/, '
') + end + end +end diff --git a/samples/client/petstore/ruby/lib/petstore/swagger.rb b/samples/client/petstore/ruby/lib/petstore/swagger.rb deleted file mode 100644 index 4f1433d3286..00000000000 --- a/samples/client/petstore/ruby/lib/petstore/swagger.rb +++ /dev/null @@ -1,76 +0,0 @@ -module Petstore - module Swagger - class << self - attr_accessor :logger - - # A Swagger configuration object. Must act like a hash and return sensible - # values for all Swagger configuration options. See Swagger::Configuration. - attr_accessor :configuration - - attr_accessor :resources - - # Call this method to modify defaults in your initializers. - # - # @example - # Swagger.configure do |config| - # config.api_key['api_key'] = '1234567890abcdef' # api key authentication - # config.username = 'wordlover' # http basic authentication - # config.password = 'i<3words' # http basic authentication - # config.format = 'json' # optional, defaults to 'json' - # end - # - def configure - yield(configuration) if block_given? - - self.logger = configuration.logger - - # remove :// from scheme - configuration.scheme.sub!(/:\/\//, '') - - # remove http(s):// and anything after a slash - configuration.host.sub!(/https?:\/\//, '') - configuration.host = configuration.host.split('/').first - - # Add leading and trailing slashes to base_path - configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/') - configuration.base_path = "" if configuration.base_path == "/" - end - - def authenticated? - !Swagger.configuration.auth_token.nil? - end - - def de_authenticate - Swagger.configuration.auth_token = nil - end - - def authenticate - return if Swagger.authenticated? - - if Swagger.configuration.username.nil? || Swagger.configuration.password.nil? - raise ApiError, "Username and password are required to authenticate." - end - - request = Swagger::Request.new( - :get, - "account/authenticate/{username}", - :params => { - :username => Swagger.configuration.username, - :password => Swagger.configuration.password - } - ) - - response_body = request.response.body - Swagger.configuration.auth_token = response_body['token'] - end - - def last_response - Thread.current[:swagger_last_response] - end - - def last_response=(response) - Thread.current[:swagger_last_response] = response - end - end - end -end diff --git a/samples/client/petstore/ruby/lib/petstore/swagger/api_error.rb b/samples/client/petstore/ruby/lib/petstore/swagger/api_error.rb deleted file mode 100644 index 9eab46b6eec..00000000000 --- a/samples/client/petstore/ruby/lib/petstore/swagger/api_error.rb +++ /dev/null @@ -1,26 +0,0 @@ -module Petstore - module Swagger - class ApiError < StandardError - attr_reader :code, :response_headers, :response_body - - # Usage examples: - # ApiError.new - # ApiError.new("message") - # ApiError.new(:code => 500, :response_headers => {}, :response_body => "") - # ApiError.new(:code => 404, :message => "Not Found") - def initialize(arg = nil) - if arg.is_a? Hash - arg.each do |k, v| - if k.to_s == 'message' - super v - else - instance_variable_set "@#{k}", v - end - end - else - super arg - end - end - end - end -end diff --git a/samples/client/petstore/ruby/lib/petstore/swagger/configuration.rb b/samples/client/petstore/ruby/lib/petstore/swagger/configuration.rb deleted file mode 100644 index d7cc3d734e0..00000000000 --- a/samples/client/petstore/ruby/lib/petstore/swagger/configuration.rb +++ /dev/null @@ -1,101 +0,0 @@ -require 'logger' - -module Petstore - module Swagger - class Configuration - attr_accessor :scheme, :host, :base_path, :user_agent, :format, :auth_token, :inject_format, :force_ending_format - - # Defines the username used with HTTP basic authentication. - # - # @return [String] - attr_accessor :username - - # Defines the password used with HTTP basic authentication. - # - # @return [String] - attr_accessor :password - - # Defines API keys used with API Key authentications. - # - # @return [Hash] key: parameter name, value: parameter value (API key) - # - # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string) - # config.api_key['api_key'] = 'xxx' - attr_accessor :api_key - - # Defines API key prefixes used with API Key authentications. - # - # @return [Hash] key: parameter name, value: API key prefix - # - # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers) - # config.api_key_prefix['api_key'] = 'Token' - attr_accessor :api_key_prefix - - # Set this to false to skip verifying SSL certificate when calling API from https server. - # Default to true. - # - # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. - # - # @return [true, false] - attr_accessor :verify_ssl - - # Set this to customize the certificate file to verify the peer. - # - # @return [String] the path to the certificate file - # - # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code: - # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 - attr_accessor :ssl_ca_cert - - # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response - # details will be logged with `logger.debug` (see the `logger` attribute). - # Default to false. - # - # @return [true, false] - attr_accessor :debug - - # Defines the logger used for debugging. - # Default to `Rails.logger` (when in Rails) or logging to STDOUT. - # - # @return [#debug] - attr_accessor :logger - - # Defines the temporary folder to store downloaded files - # (for API endpoints that have file response). - # Default to use `Tempfile`. - # - # @return [String] - attr_accessor :temp_folder_path - - # Defines the headers to be used in HTTP requests of all API calls by default. - # - # @return [Hash] - attr_accessor :default_headers - - # Defaults go in here.. - def initialize - @format = 'json' - @scheme = 'http' - @host = 'petstore.swagger.io' - @base_path = '/v2' - @user_agent = "ruby-swagger-#{Swagger::VERSION}" - @inject_format = false - @force_ending_format = false - - @default_headers = { - 'Content-Type' => "application/#{@format.downcase}", - 'User-Agent' => @user_agent - } - - # keys for API key authentication (param-name => api-key) - @api_key = {} - @api_key_prefix = {} - - @verify_ssl = true - - @debug = false - @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT) - end - end - end -end diff --git a/samples/client/petstore/ruby/lib/petstore/swagger/request.rb b/samples/client/petstore/ruby/lib/petstore/swagger/request.rb deleted file mode 100644 index ecb8cff5643..00000000000 --- a/samples/client/petstore/ruby/lib/petstore/swagger/request.rb +++ /dev/null @@ -1,213 +0,0 @@ -require 'uri' -require 'typhoeus' - -module Petstore - module Swagger - class Request - attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params, :auth_names, :response - - # All requests must have an HTTP method and a path - # Optionals parameters are :params, :headers, :body, :format, :host - def initialize(http_method, path, attributes = {}) - @http_method = http_method.to_sym.downcase - @path = path - - attributes.each { |name, value| send "#{name}=", value } - - @format ||= Swagger.configuration.format - @params ||= {} - - # Apply default headers - @headers = Swagger.configuration.default_headers.merge(@headers || {}) - - # Stick in the auth token if there is one - if Swagger.authenticated? - @headers.merge!({:auth_token => Swagger.configuration.auth_token}) - end - - update_params_for_auth! - - end - - - # Update hearder and query params based on authentication settings. - def update_params_for_auth! - (@auth_names || []).each do |auth_name| - case auth_name - when 'api_key' - @headers ||= {} - @headers['api_key'] = get_api_key_with_prefix('api_key') - when 'petstore_auth' - # TODO: support oauth - - end - end - end - - - # Get API key (with prefix if set). - # @param [String] param_name the parameter name of API key auth - def get_api_key_with_prefix(param_name) - if Swagger.configuration.api_key_prefix[param_name] - "#{Swagger.configuration.api_key_prefix[param_name]} #{Swagger.configuration.api_key[param_name]}" - else - Swagger.configuration.api_key[param_name] - end - end - - # Construct the request URL. - def url(options = {}) - _path = self.interpreted_path - _path = "/#{_path}" unless _path.start_with?('/') - "#{Swagger.configuration.scheme}://#{Swagger.configuration.host}#{_path}" - end - - # Iterate over the params hash, injecting any path values into the path string - # e.g. /word.{format}/{word}/entries => /word.json/cat/entries - def interpreted_path - p = self.path.dup - - # Stick a .{format} placeholder into the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words.{format}/blah - if Swagger.configuration.inject_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = p.sub(/^(\/?\w+)/, "\\1.#{format}") - end - end - - # Stick a .{format} placeholder on the end of the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words/blah.{format} - if Swagger.configuration.force_ending_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = "#{p}.#{format}" - end - end - - p = p.sub("{format}", self.format.to_s) - - URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/') - end - - # If body is an object, JSONify it before making the actual request. - # For form parameters, remove empty value - def outgoing_body - # http form - if headers['Content-Type'] == 'application/x-www-form-urlencoded' - data = form_params.dup - data.each do |key, value| - data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter - end - elsif @body # http body is JSON - data = @body.is_a?(String) ? @body : @body.to_json - else - data = nil - end - - if Swagger.configuration.debug - Swagger.logger.debug "HTTP request body param ~BEGIN~\n#{data}\n~END~\n" - end - - data - end - - def make - request_options = { - :method => self.http_method, - :headers => self.headers, - :params => self.params, - :ssl_verifypeer => Swagger.configuration.verify_ssl, - :cainfo => Swagger.configuration.ssl_ca_cert, - :verbose => Swagger.configuration.debug - } - - if [:post, :patch, :put, :delete].include?(self.http_method) - request_options.update :body => self.outgoing_body - end - - raw = Typhoeus::Request.new(self.url, request_options).run - @response = Response.new(raw) - - if Swagger.configuration.debug - Swagger.logger.debug "HTTP response body ~BEGIN~\n#{@response.body}\n~END~\n" - end - - # record as last response - Swagger.last_response = @response - - unless @response.success? - fail ApiError.new(:code => @response.code, - :response_headers => @response.headers, - :response_body => @response.body), - @response.status_message - end - - @response - end - - def response_code_pretty - return unless @response - @response.code.to_s - end - - def response_headers_pretty - return unless @response - # JSON.pretty_generate(@response.headers).gsub(/\n/, '
') # <- This was for RestClient - @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus - end - - # return 'Accept' based on an array of accept provided - # @param [Array] header_accept_array Array fo 'Accept' - # @return String Accept (e.g. application/json) - def self.select_header_accept header_accept_array - if header_accept_array.empty? - return - elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # look for json data by default - else - header_accept_array.join(',') - end - end - - # return the content type based on an array of content-type provided - # @param [Array] content_type_array Array fo content-type - # @return String Content-Type (e.g. application/json) - def self.select_header_content_type content_type_array - if content_type_array.empty? - 'application/json' # use application/json by default - elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # use application/json if it's included - else - content_type_array[0]; # otherwise, use the first one - end - end - - # static method to convert object (array, hash, object, etc) to JSON string - # @param model object to be converted into JSON string - # @return string JSON string representation of the object - def self.object_to_http_body model - return if model.nil? - _body = nil - if model.is_a?(Array) - _body = model.map{|m| object_to_hash(m) } - else - _body = object_to_hash(model) - end - _body.to_json - end - - # static method to convert object(non-array) to hash - # @param obj object to be converted into JSON string - # @return string JSON string representation of the object - def self.object_to_hash obj - if obj.respond_to?(:to_hash) - obj.to_hash - else - obj - end - end - - end - end -end diff --git a/samples/client/petstore/ruby/lib/petstore/swagger/response.rb b/samples/client/petstore/ruby/lib/petstore/swagger/response.rb deleted file mode 100644 index 2ab9be1a5b9..00000000000 --- a/samples/client/petstore/ruby/lib/petstore/swagger/response.rb +++ /dev/null @@ -1,156 +0,0 @@ -module Petstore - module Swagger - class Response - require 'json' - require 'date' - require 'tempfile' - - attr_accessor :raw - - def initialize(raw) - self.raw = raw - end - - def code - raw.code - end - - def status_message - raw.status_message - end - - def body - raw.body - end - - def success? - raw.success? - end - - # Deserialize the raw response body to the given return type. - # - # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]" - def deserialize(return_type) - return nil if body.nil? || body.empty? - - # handle file downloading - save response body into a tmp file and return the File instance - return download_file if return_type == 'File' - - # ensuring a default content type - content_type = raw.headers['Content-Type'] || 'application/json' - - unless content_type.start_with?('application/json') - fail "Content-Type is not supported: #{content_type}" - end - - begin - data = JSON.parse("[#{body}]", :symbolize_names => true)[0] - rescue JSON::ParserError => e - if %w(String Date DateTime).include?(return_type) - data = body - else - raise e - end - end - - convert_to_type data, return_type - end - - # Convert data to the given return type. - def convert_to_type(data, return_type) - return nil if data.nil? - case return_type - 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 - when 'Date' - # parse date time (expecting ISO 8601 format) - Date.parse data - when 'Object' - # generic object, return directly - data - when /\AArray<(.+)>\z/ - # e.g. Array - sub_type = $1 - data.map {|item| convert_to_type(item, sub_type) } - when /\AHash\\z/ - # e.g. Hash - sub_type = $1 - {}.tap do |hash| - data.each {|k, v| hash[k] = convert_to_type(v, sub_type) } - end - else - # models, e.g. Pet - Petstore.const_get(return_type).new.tap do |model| - model.build_from_hash data - end - end - end - - # Save response body into a file in (the defined) temporary folder, using the filename - # from the "Content-Disposition" header if provided, otherwise a random filename. - # - # @see Configuration#temp_folder_path - # @return [File] the file downloaded - def download_file - tmp_file = Tempfile.new '', Swagger.configuration.temp_folder_path - content_disposition = raw.headers['Content-Disposition'] - if content_disposition - filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] - path = File.join File.dirname(tmp_file), filename - else - path = tmp_file.path - end - # close and delete temp file - tmp_file.close! - - File.open(path, 'w') { |file| file.write(raw.body) } - Swagger.logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards" - return File.new(path) - end - - # `headers_hash` is a Typhoeus-specific extension of Hash, - # so simplify it back into a regular old Hash. - def headers - h = {} - raw.headers_hash.each {|k,v| h[k] = v } - h - end - - # Extract the response format from the header hash - # e.g. {'Content-Type' => 'application/json'} - def format - headers['Content-Type'].split("/").last.downcase - end - - def json? - format == 'json' - end - - def xml? - format == 'xml' - end - - def pretty_body - return unless body - if format == 'json' - JSON.pretty_generate(JSON.parse(body)).gsub(/\n/, '
') - else - body - end - end - - def pretty_headers - JSON.pretty_generate(headers).gsub(/\n/, '
') - end - end - end -end diff --git a/samples/client/petstore/ruby/lib/petstore/swagger/version.rb b/samples/client/petstore/ruby/lib/petstore/swagger/version.rb deleted file mode 100644 index ff3c48bb59e..00000000000 --- a/samples/client/petstore/ruby/lib/petstore/swagger/version.rb +++ /dev/null @@ -1,5 +0,0 @@ -module Petstore - module Swagger - VERSION = "1.0.0" - end -end diff --git a/samples/client/petstore/ruby/lib/petstore/version.rb b/samples/client/petstore/ruby/lib/petstore/version.rb new file mode 100644 index 00000000000..fed78553ed3 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/version.rb @@ -0,0 +1,3 @@ +module Petstore + VERSION = "1.0.0" +end diff --git a/samples/client/petstore/ruby/petstore.gemspec b/samples/client/petstore/ruby/petstore.gemspec index 40a169d1741..6e41479fe46 100644 --- a/samples/client/petstore/ruby/petstore.gemspec +++ b/samples/client/petstore/ruby/petstore.gemspec @@ -1,10 +1,10 @@ # -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) -require "petstore/swagger/version" +require "petstore/version" Gem::Specification.new do |s| s.name = "petstore" - s.version = Petstore::Swagger::VERSION + s.version = Petstore::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Zeke Sikelianos", "Tony Tam"] s.email = ["zeke@wordnik.com", "fehguy@gmail.com"] From a75b05b952f76a575a23ef4af2bcbaa70c1d682c Mon Sep 17 00:00:00 2001 From: xhh Date: Tue, 30 Jun 2015 14:32:55 +0800 Subject: [PATCH 05/17] Update tests with latest code --- .../petstore/ruby/spec/api_client_spec.rb | 53 ++++++++++++++++++ samples/client/petstore/ruby/spec/pet_spec.rb | 24 ++++---- .../client/petstore/ruby/spec/request_spec.rb | 18 +++--- .../petstore/ruby/spec/response_spec.rb | 11 +--- .../client/petstore/ruby/spec/spec_helper.rb | 22 +++----- .../client/petstore/ruby/spec/store_spec.rb | 8 +-- .../client/petstore/ruby/spec/swagger_spec.rb | 56 ------------------- 7 files changed, 90 insertions(+), 102 deletions(-) create mode 100644 samples/client/petstore/ruby/spec/api_client_spec.rb delete mode 100644 samples/client/petstore/ruby/spec/swagger_spec.rb diff --git a/samples/client/petstore/ruby/spec/api_client_spec.rb b/samples/client/petstore/ruby/spec/api_client_spec.rb new file mode 100644 index 00000000000..f66dcdd68fd --- /dev/null +++ b/samples/client/petstore/ruby/spec/api_client_spec.rb @@ -0,0 +1,53 @@ +# require 'spec_helper' +require File.dirname(__FILE__) + '/spec_helper' + +describe Petstore::ApiClient do + + context 'initialization' do + + context 'URL stuff' do + + context 'host' do + it 'removes http from host' do + c = Petstore::ApiClient.new + c.configure {|c| c.host = 'http://example.com' } + c.host.should == 'example.com' + end + + it 'removes https from host' do + c = Petstore::ApiClient.new {|c| c.host = 'https://wookiee.com' } + c.host.should == 'wookiee.com' + end + + it 'removes trailing path from host' do + c = Petstore::ApiClient.new + c.configure {|c| c.host = 'hobo.com/v4' } + c.host.should == 'hobo.com' + end + end + + context 'base_path' do + it "prepends a slash to base_path" do + c = Petstore::ApiClient.new + c.configure {|c| c.base_path = 'v4/dog' } + c.base_path.should == '/v4/dog' + end + + it "doesn't prepend a slash if one is already there" do + c = Petstore::ApiClient.new + c.configure {|c| c.base_path = '/v4/dog' } + c.base_path.should == '/v4/dog' + end + + it "ends up as a blank string if nil" do + c = Petstore::ApiClient.new + c.configure {|c| c.base_path = nil } + c.base_path.should == '' + end + end + + end + + end + +end diff --git a/samples/client/petstore/ruby/spec/pet_spec.rb b/samples/client/petstore/ruby/spec/pet_spec.rb index 8c33c3a9cde..c288ec2192e 100644 --- a/samples/client/petstore/ruby/spec/pet_spec.rb +++ b/samples/client/petstore/ruby/spec/pet_spec.rb @@ -3,8 +3,8 @@ require 'json' describe "Pet" do before do - configure_swagger - prepare_pet + @pet_api = Petstore::PetApi.new(API_CLIENT) + prepare_pet @pet_api end describe "pet methods" do @@ -42,7 +42,7 @@ describe "Pet" do end it "should fetch a pet object" do - pet = Petstore::PetApi.get_pet_by_id(10002) + pet = @pet_api.get_pet_by_id(10002) pet.should be_a(Petstore::Pet) pet.id.should == 10002 pet.name.should == "RUBY UNIT TESTING" @@ -52,9 +52,9 @@ describe "Pet" do it "should not find a pet that does not exist" do begin - Petstore::PetApi.get_pet_by_id(-10002) + @pet_api.get_pet_by_id(-10002) fail 'it should raise error' - rescue Petstore::Swagger::ApiError => e + rescue Petstore::ApiError => e e.code.should == 404 e.message.should == 'Not Found' e.response_body.should == '{"code":1,"type":"error","message":"Pet not found"}' @@ -64,7 +64,7 @@ describe "Pet" do end it "should find pets by status" do - pets = Petstore::PetApi.find_pets_by_status(:status => 'available') + pets = @pet_api.find_pets_by_status(:status => 'available') pets.length.should >= 3 pets.each do |pet| pet.should be_a(Petstore::Pet) @@ -73,12 +73,12 @@ describe "Pet" do end it "should not find a pet with invalid status" do - pets = Petstore::PetApi.find_pets_by_status(:status => 'invalid-status') + pets = @pet_api.find_pets_by_status(:status => 'invalid-status') pets.length.should == 0 end it "should find a pet by status" do - pets = Petstore::PetApi.find_pets_by_status(:status => "available,sold") + pets = @pet_api.find_pets_by_status(:status => "available,sold") pets.each do |pet| if pet.status != 'available' && pet.status != 'sold' raise "pet status wasn't right" @@ -88,20 +88,20 @@ describe "Pet" do it "should update a pet" do pet = Petstore::Pet.new({'id' => 10002, 'status' => 'sold'}) - Petstore::PetApi.add_pet(:body => pet) + @pet_api.add_pet(:body => pet) - fetched = Petstore::PetApi.get_pet_by_id(10002) + fetched = @pet_api.get_pet_by_id(10002) fetched.id.should == 10002 fetched.status.should == 'sold' end it "should create a pet" do pet = Petstore::Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING") - result = Petstore::PetApi.add_pet(:body => pet) + result = @pet_api.add_pet(:body => pet) # nothing is returned result.should be_nil - pet = Petstore::PetApi.get_pet_by_id(10002) + pet = @pet_api.get_pet_by_id(10002) pet.id.should == 10002 pet.name.should == "RUBY UNIT TESTING" end diff --git a/samples/client/petstore/ruby/spec/request_spec.rb b/samples/client/petstore/ruby/spec/request_spec.rb index 8eeac549f93..b4bf64c8f39 100644 --- a/samples/client/petstore/ruby/spec/request_spec.rb +++ b/samples/client/petstore/ruby/spec/request_spec.rb @@ -1,9 +1,9 @@ require 'spec_helper' -describe Petstore::Swagger::Request do +describe Petstore::Request do before(:each) do - Petstore::Swagger.configure do |config| + @api_client = Petstore::ApiClient.new do |config| inject_format = true config.api_key['api_key'] = 'special-key' config.host = 'petstore.swagger.io' @@ -15,7 +15,7 @@ describe Petstore::Swagger::Request do @default_params = { :params => {:foo => "1", :bar => "2"} } - @request = Petstore::Swagger::Request.new(@default_http_method, @default_path, @default_params) + @request = Petstore::Request.new(@api_client, @default_http_method, @default_path, @default_params) end describe "initialization" do @@ -29,7 +29,7 @@ describe Petstore::Swagger::Request do end it "allows params to be nil" do - @request = Petstore::Swagger::Request.new(@default_http_method, @default_path, :params => nil) + @request = Petstore::Request.new(@api_client, @default_http_method, @default_path, :params => nil) @request.params.should == {} end @@ -60,7 +60,7 @@ describe Petstore::Swagger::Request do describe "path" do it "accounts for a total absence of format in the path string" do - @request = Petstore::Swagger::Request.new(:get, "/word.{format}/cat/entries", @default_params.merge({ + @request = Petstore::Request.new(@api_client, :get, "/word.{format}/cat/entries", @default_params.merge({ :format => "xml", :params => { } @@ -69,7 +69,7 @@ describe Petstore::Swagger::Request do end it "does string substitution (format) on path params" do - @request = Petstore::Swagger::Request.new(:get, "/word.{format}/cat/entries", @default_params.merge({ + @request = Petstore::Request.new(@api_client, :get, "/word.{format}/cat/entries", @default_params.merge({ :format => "xml", :params => { } @@ -78,7 +78,7 @@ describe Petstore::Swagger::Request do end it "URI encodes the path" do - @request = Petstore::Swagger::Request.new(:get, "word.{format}/bill gates/definitions", @default_params.merge({ + @request = Petstore::Request.new(@api_client, :get, "word.{format}/bill gates/definitions", @default_params.merge({ :params => { :word => "bill gates" } @@ -90,7 +90,7 @@ describe Petstore::Swagger::Request do describe "#update_params_for_auth!" do it "sets header api-key parameter with prefix" do - Petstore::Swagger.configure do |config| + @api_client.configure do |config| inject_format = true config.api_key_prefix['api_key'] = 'PREFIX' end @@ -100,7 +100,7 @@ describe Petstore::Swagger::Request do end it "sets header api-key parameter without prefix" do - Petstore::Swagger.configure do |config| + @api_client.configure do |config| inject_format = true config.api_key_prefix['api_key'] = nil end diff --git a/samples/client/petstore/ruby/spec/response_spec.rb b/samples/client/petstore/ruby/spec/response_spec.rb index c583b413fca..4aeea0ea832 100644 --- a/samples/client/petstore/ruby/spec/response_spec.rb +++ b/samples/client/petstore/ruby/spec/response_spec.rb @@ -1,18 +1,13 @@ require 'spec_helper' -describe Petstore::Swagger::Response do - - before do - configure_swagger - prepare_pet - end +describe Petstore::Response do before(:each) do VCR.use_cassette('pet_resource', :record => :new_episodes) do @raw = Typhoeus::Request.get("http://petstore.swagger.io/v2/pet/10002") end - @response = Petstore::Swagger::Response.new(@raw) + @response = Petstore::Response.new(API_CLIENT, @raw) end describe "initialization" do @@ -43,7 +38,7 @@ describe Petstore::Swagger::Response do @raw = Typhoeus::Request.get("http://petstore.swagger.io/v2/pet/10002", :headers => {'Accept'=> "application/xml"}) end - @response = Petstore::Swagger::Response.new(@raw) + @response = Petstore::Response.new(API_CLIENT, @raw) @response.format.should == 'xml' @response.xml?.should == true end diff --git a/samples/client/petstore/ruby/spec/spec_helper.rb b/samples/client/petstore/ruby/spec/spec_helper.rb index 55279384e61..f8e5992a342 100644 --- a/samples/client/petstore/ruby/spec/spec_helper.rb +++ b/samples/client/petstore/ruby/spec/spec_helper.rb @@ -36,40 +36,36 @@ end # help #end -def configure_swagger - Petstore::Swagger.configure do |config| - config.api_key['api_key'] = 'special-key' - config.host = 'petstore.swagger.io' - config.base_path = '/v2' - end +API_CLIENT = Petstore::ApiClient.new do |config| + config.api_key['api_key'] = 'special-key' + config.host = 'petstore.swagger.io' + config.base_path = '/v2' end # always delete and then re-create the pet object with 10002 -def prepare_pet +def prepare_pet(pet_api) # remove the pet - Petstore::PetApi.delete_pet(10002) + pet_api.delete_pet(10002) # recreate the pet category = Petstore::Category.new('id' => 20002, 'name' => 'category test') tag = Petstore::Tag.new('id' => 30002, 'name' => 'tag test') pet = Petstore::Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING", 'photo_urls' => 'photo url', 'category' => category, 'tags' => [tag], 'status' => 'pending') - Petstore::PetApi.add_pet(:'body'=> pet) + pet_api.add_pet(:'body'=> pet) end # always delete and then re-create the store order -def prepare_store +def prepare_store(store_api) order = Petstore::Order.new("id" => 10002, "petId" => 10002, "quantity" => 789, "shipDate" => "2015-04-06T23:42:01.678Z", "status" => "placed", "complete" => false) - Petstore::StoreApi.place_order(:body => order) + store_api.place_order(:body => order) end -configure_swagger - # A random string to tack onto stuff to ensure we're not seeing # data from a previous test run RAND = ("a".."z").to_a.sample(8).join diff --git a/samples/client/petstore/ruby/spec/store_spec.rb b/samples/client/petstore/ruby/spec/store_spec.rb index 8c59de39fec..1e0f035d143 100644 --- a/samples/client/petstore/ruby/spec/store_spec.rb +++ b/samples/client/petstore/ruby/spec/store_spec.rb @@ -2,17 +2,17 @@ require 'spec_helper' describe "Store" do before do - configure_swagger - prepare_store + @api = Petstore::StoreApi.new(API_CLIENT) + prepare_store @api end it "should fetch an order" do - item = Petstore::StoreApi.get_order_by_id(10002) + item = @api.get_order_by_id(10002) item.id.should == 10002 end it "should featch the inventory" do - result = Petstore::StoreApi.get_inventory + result = @api.get_inventory result.should be_a(Hash) result.should_not be_empty result.each do |k, v| diff --git a/samples/client/petstore/ruby/spec/swagger_spec.rb b/samples/client/petstore/ruby/spec/swagger_spec.rb deleted file mode 100644 index 957da5e20a6..00000000000 --- a/samples/client/petstore/ruby/spec/swagger_spec.rb +++ /dev/null @@ -1,56 +0,0 @@ -# require 'spec_helper' -require File.dirname(__FILE__) + '/spec_helper' - -describe Petstore::Swagger do - - before(:each) do - configure_swagger - end - - after(:each) do - end - - context 'initialization' do - - context 'URL stuff' do - - context 'host' do - it 'removes http from host' do - Petstore::Swagger.configure {|c| c.host = 'http://example.com' } - Petstore::Swagger.configuration.host.should == 'example.com' - end - - it 'removes https from host' do - Petstore::Swagger.configure {|c| c.host = 'https://wookiee.com' } - Petstore::Swagger.configuration.host.should == 'wookiee.com' - end - - it 'removes trailing path from host' do - Petstore::Swagger.configure {|c| c.host = 'hobo.com/v4' } - Petstore::Swagger.configuration.host.should == 'hobo.com' - end - end - - context 'base_path' do - it "prepends a slash to base_path" do - Petstore::Swagger.configure {|c| c.base_path = 'v4/dog' } - Petstore::Swagger.configuration.base_path.should == '/v4/dog' - end - - it "doesn't prepend a slash if one is already there" do - Petstore::Swagger.configure {|c| c.base_path = '/v4/dog' } - Petstore::Swagger.configuration.base_path.should == '/v4/dog' - end - - it "ends up as a blank string if nil" do - Petstore::Swagger.configure {|c| c.base_path = nil } - Petstore::Swagger.configuration.base_path.should == '' - end - - end - - end - - end - -end From 5bfae7b78c216e7aec47e8074f780611385ad692 Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 27 Jul 2015 10:32:51 +0800 Subject: [PATCH 06/17] Ruby: use a default ApiClient when not provided --- modules/swagger-codegen/src/main/resources/ruby/api.mustache | 4 ++-- .../src/main/resources/ruby/api_client.mustache | 5 +++++ samples/client/petstore/ruby/README.md | 4 ++-- samples/client/petstore/ruby/lib/petstore/api/pet_api.rb | 4 ++-- samples/client/petstore/ruby/lib/petstore/api/store_api.rb | 4 ++-- samples/client/petstore/ruby/lib/petstore/api/user_api.rb | 4 ++-- samples/client/petstore/ruby/lib/petstore/api_client.rb | 5 +++++ 7 files changed, 20 insertions(+), 10 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index e1005a90159..6b459fe013d 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -5,8 +5,8 @@ module {{moduleName}} class {{classname}} attr_accessor :api_client - def initialize(api_client = ApiClient.new) - @api_client = api_client + def initialize(api_client = nil) + @api_client = api_client || ApiClient.default end {{#operation}} diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache index e8fc5b9440a..600ff190b27 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache @@ -110,6 +110,11 @@ module {{moduleName}} configure(&block) end + # Default API client. + def self.default + @@default ||= ApiClient.new + end + # Call this method to modify defaults in your initializers. def configure yield(self) if block_given? diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index b251d14faf7..ad85f74315b 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -42,7 +42,7 @@ ruby -Ilib script.rb ```ruby require 'petstore' -api_client = Petstore::ApiClient.new do |client| +Petstore::ApiClient.default.configure do |client| client.api_key['api_key'] = 'special-key' client.host = 'petstore.swagger.io' client.base_path = '/v2' @@ -50,7 +50,7 @@ api_client = Petstore::ApiClient.new do |client| client.debugging = true end -pet_api = Petstore::PetApi.new(api_client) +pet_api = Petstore::PetApi.new pet = pet_api.get_pet_by_id(5) puts pet.to_body ``` diff --git a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb index b50b56e6343..419aec9f044 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb @@ -4,8 +4,8 @@ module Petstore class PetApi attr_accessor :api_client - def initialize(api_client = ApiClient.new) - @api_client = api_client + def initialize(api_client = nil) + @api_client = api_client || ApiClient.default end diff --git a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb index 3462cd8f7de..ada198f46a3 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb @@ -4,8 +4,8 @@ module Petstore class StoreApi attr_accessor :api_client - def initialize(api_client = ApiClient.new) - @api_client = api_client + def initialize(api_client = nil) + @api_client = api_client || ApiClient.default end diff --git a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb index 5664f735f01..375baffc3ef 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb @@ -4,8 +4,8 @@ module Petstore class UserApi attr_accessor :api_client - def initialize(api_client = ApiClient.new) - @api_client = api_client + def initialize(api_client = nil) + @api_client = api_client || ApiClient.default end diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index 569003fa133..2f4b76d5422 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -110,6 +110,11 @@ module Petstore configure(&block) end + # Default API client. + def self.default + @@default ||= ApiClient.new + end + # Call this method to modify defaults in your initializers. def configure yield(self) if block_given? From 47c8597d36a9bc0983ba5c40e2489bb094f9f076 Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 27 Jul 2015 16:34:51 +0800 Subject: [PATCH 07/17] Ruby: move request/response logic to api_client --- .../codegen/languages/RubyClientCodegen.java | 2 - .../src/main/resources/ruby/api.mustache | 24 +- .../main/resources/ruby/api_client.mustache | 255 +++++++++++++++++- .../src/main/resources/ruby/gem.mustache | 2 - .../src/main/resources/ruby/request.mustache | 208 -------------- .../src/main/resources/ruby/response.mustache | 155 ----------- 6 files changed, 269 insertions(+), 377 deletions(-) delete mode 100644 modules/swagger-codegen/src/main/resources/ruby/request.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/ruby/response.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java index 352307220a6..c82b5f7b6ce 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java @@ -109,8 +109,6 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("gem.mustache", libFolder, gemName + ".rb")); String gemFolder = libFolder + File.separator + gemName; supportingFiles.add(new SupportingFile("api_client.mustache", gemFolder, "api_client.rb")); - supportingFiles.add(new SupportingFile("request.mustache", gemFolder, "request.rb")); - supportingFiles.add(new SupportingFile("response.mustache", gemFolder, "response.rb")); supportingFiles.add(new SupportingFile("api_error.mustache", gemFolder, "api_error.rb")); supportingFiles.add(new SupportingFile("version.mustache", gemFolder, "version.rb")); String modelFolder = gemFolder + File.separator + modelPackage.replace("/", File.separator); diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index 6b459fe013d..e1a6789c54f 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -45,11 +45,11 @@ module {{moduleName}} # HTTP header 'Accept' (if needed) _header_accept = [{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type){{#headerParams}}{{#required}} + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type){{#headerParams}}{{#required}} header_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/headerParams}}{{#headerParams}}{{^required}} header_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/headerParams}} @@ -60,20 +60,30 @@ module {{moduleName}} # http body (model) {{^bodyParam}}post_body = nil - {{/bodyParam}}{{#bodyParam}}post_body = Request.object_to_http_body({{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}) + {{/bodyParam}}{{#bodyParam}}post_body = @api_client.object_to_http_body({{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}) {{/bodyParam}} auth_names = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}] - {{#returnType}}response = Request.new(@api_client, :{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - result = response.deserialize('{{{returnType}}}') + {{#returnType}}result = @api_client.call_api(:{{httpMethod}}, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => '{{{returnType}}}') if @api_client.debugging @api_client.logger.debug "API called: {{classname}}#{{nickname}}. Result: #{result.inspect}" end - result{{/returnType}}{{^returnType}}Request.new(@api_client, :{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + return result{{/returnType}}{{^returnType}}@api_client.call_api(:{{httpMethod}}, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) if @api_client.debugging @api_client.logger.debug "API called: {{classname}}#{{nickname}}" end - nil{{/returnType}} + return nil{{/returnType}} end {{/operation}} end diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache index 600ff190b27..e6cc8fac49a 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache @@ -1,9 +1,13 @@ -require 'logger' +require 'date' require 'json' +require 'logger' +require 'tempfile' +require 'typhoeus' +require 'uri' module {{moduleName}} class ApiClient - attr_accessor :scheme, :host, :base_path, :user_agent, :format, :auth_token, :inject_format, :force_ending_format + attr_accessor :scheme, :host, :base_path, :user_agent # Defines the username used with HTTP basic authentication. # @@ -82,7 +86,6 @@ module {{moduleName}} # client.api_key['api_key'] = 'your key' # api key authentication # client.username = 'your username' # username for http basic authentication # client.password = 'your password' # password for http basic authentication - # client.format = 'json' # optional, defaults to 'json' # end def initialize(&block) @format = 'json' @@ -131,9 +134,255 @@ module {{moduleName}} @base_path = "" if @base_path == "/" end + def call_api(http_method, path, opts = {}) + request = build_request(http_method, path, opts) + response = request.run + + # record as last response + @last_response = response + + if debugging + logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" + end + + unless response.success? + fail ApiError.new(:code => response.code, + :response_headers => response.headers, + :response_body => response.body), + response.status_message + end + + if opts[:return_type] + return deserialize(response, opts[:return_type]) + else + return nil + end + end + + def build_request(http_method, path, opts = {}) + url = build_request_url(path) + http_method = http_method.to_sym.downcase + + header_params = @default_headers.merge(opts[:header_params] || {}) + query_params = opts[:query_params] || {} + form_params = opts[:form_params] || {} + + {{#hasAuthMethods}} + update_params_for_auth! header_params, query_params, opts[:auth_names] + {{/hasAuthMethods}} + + req_opts = { + :method => http_method, + :headers => header_params, + :params => query_params, + :ssl_verifypeer => @verify_ssl, + :cainfo => @ssl_ca_cert, + :verbose => @debugging + } + + if [:post, :patch, :put, :delete].include?(http_method) + req_body = build_request_body(header_params, form_params, opts[:body]) + req_opts.update :body => req_body + if debugging + logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n" + end + end + + Typhoeus::Request.new(url, req_opts) + end + + # Deserialize the response to the given return type. + # + # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]" + def deserialize(response, return_type) + body = response.body + return nil if body.nil? || body.empty? + + # handle file downloading - save response body into a tmp file and return the File instance + return download_file(response) if return_type == 'File' + + # ensuring a default content type + content_type = response.headers['Content-Type'] || 'application/json' + + unless content_type.start_with?('application/json') + fail "Content-Type is not supported: #{content_type}" + end + + begin + data = JSON.parse("[#{body}]", :symbolize_names => true)[0] + rescue JSON::ParserError => e + if %w(String Date DateTime).include?(return_type) + data = body + else + raise e + end + end + + convert_to_type data, return_type + end + + # Convert data to the given return type. + def convert_to_type(data, return_type) + return nil if data.nil? + case return_type + 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 + when 'Date' + # parse date time (expecting ISO 8601 format) + Date.parse data + when 'Object' + # generic object, return directly + data + when /\AArray<(.+)>\z/ + # e.g. Array + sub_type = $1 + data.map {|item| convert_to_type(item, sub_type) } + when /\AHash\\z/ + # e.g. Hash + sub_type = $1 + {}.tap do |hash| + data.each {|k, v| hash[k] = convert_to_type(v, sub_type) } + end + else + # models, e.g. Pet + {{moduleName}}.const_get(return_type).new.tap do |model| + model.build_from_hash data + end + end + end + + # Save response body into a file in (the defined) temporary folder, using the filename + # from the "Content-Disposition" header if provided, otherwise a random filename. + # + # @see Configuration#temp_folder_path + # @return [File] the file downloaded + def download_file(response) + tmp_file = Tempfile.new '', @temp_folder_path + content_disposition = response.headers['Content-Disposition'] + if content_disposition + filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] + path = File.join File.dirname(tmp_file), filename + else + path = tmp_file.path + end + # close and delete temp file + tmp_file.close! + + File.open(path, 'w') { |file| file.write(response.body) } + logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards" + return File.new(path) + end + + def build_request_url(path) + url = [host, base_path, path].join('/').gsub(/\/+/, '/') + url = "#{scheme}://#{url}" + URI.encode(url) + end + + def build_request_body(header_params, form_params, body) + # http form + if header_params['Content-Type'] == 'application/x-www-form-urlencoded' + data = form_params.dup + data.each do |key, value| + data[key] = value.to_s if value && !value.is_a?(File) + end + elsif body + data = body.is_a?(String) ? body : body.to_json + else + data = nil + end + return data + end + + {{#hasAuthMethods}} + # Update hearder and query params based on authentication settings. + def update_params_for_auth!(header_params, query_params, auth_names) + return unless auth_names + auth_names.each do |auth_name| + case auth_name + {{#authMethods}}when '{{name}}' + {{#isApiKey}}{{#isKeyInHeader}}header_params ||= {} + header_params['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInHeader}}{{#isKeyInQuery}}query_params['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}http_auth_header = 'Basic ' + ["#{@username}:#{@password}"].pack('m').delete("\r\n") + header_params['Authorization'] = http_auth_header{{/isBasic}}{{#isOAuth}}# TODO: support oauth{{/isOAuth}} + {{/authMethods}} + end + end + end + + # Get API key (with prefix if set). + # @param [String] param_name the parameter name of API key auth + def get_api_key_with_prefix(param_name) + if @api_key_prefix[param_name] + "#{@api_key_prefix[param_name]} #{@api_key[param_name]}" + else + @api_key[param_name] + end + end + {{/hasAuthMethods}} + def user_agent=(user_agent) @user_agent = user_agent @default_headers['User-Agent'] = @user_agent end + + # Return Accept header based on an array of accepts provided. + # @param [Array] accepts array for Accept + # @return [String] the Accept header (e.g. application/json) + def select_header_accept(accepts) + if accepts.empty? + return + elsif accepts.any?{ |s| s.casecmp('application/json') == 0 } + 'application/json' # look for json data by default + else + accepts.join(',') + end + end + + # Return Content-Type header based on an array of content types provided. + # @param [Array] content_types array for Content-Type + # @return [String] the Content-Type header (e.g. application/json) + def select_header_content_type(content_types) + if content_types.empty? + 'application/json' # use application/json by default + elsif content_types.any?{ |s| s.casecmp('application/json')==0 } + 'application/json' # use application/json if it's included + else + content_types[0] # otherwise, use the first one + end + end + + # Convert object (array, hash, object, etc) to JSON string. + # @param [Object] model object to be converted into JSON string + # @return [String] JSON string representation of the object + def object_to_http_body(model) + return if model.nil? + _body = nil + if model.is_a?(Array) + _body = model.map{|m| object_to_hash(m) } + else + _body = object_to_hash(model) + end + _body.to_json + end + + # Convert object(non-array) to hash. + # @param [Object] obj object to be converted into JSON string + # @return [String] JSON string representation of the object + def object_to_hash(obj) + if obj.respond_to?(:to_hash) + obj.to_hash + else + obj + end + end end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/gem.mustache b/modules/swagger-codegen/src/main/resources/ruby/gem.mustache index 41f151590d9..37203162d6b 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/gem.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/gem.mustache @@ -1,8 +1,6 @@ # Common files require '{{gemName}}/api_client' require '{{gemName}}/api_error' -require '{{gemName}}/request' -require '{{gemName}}/response' require '{{gemName}}/version' # Models diff --git a/modules/swagger-codegen/src/main/resources/ruby/request.mustache b/modules/swagger-codegen/src/main/resources/ruby/request.mustache deleted file mode 100644 index 6a7d2ac448e..00000000000 --- a/modules/swagger-codegen/src/main/resources/ruby/request.mustache +++ /dev/null @@ -1,208 +0,0 @@ -require 'uri' -require 'typhoeus' - -module {{moduleName}} - class Request - attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params, :auth_names, :response - - # All requests must have an HTTP method and a path - # Optionals parameters are :params, :headers, :body, :format, :host - def initialize(api_client, http_method, path, attributes = {}) - @api_client = api_client - - @http_method = http_method.to_sym.downcase - @path = path - - attributes.each { |name, value| send "#{name}=", value } - - @format ||= @api_client.format - @params ||= {} - - # Apply default headers - @headers = @api_client.default_headers.merge(@headers || {}) - {{#hasAuthMethods}} - update_params_for_auth! - {{/hasAuthMethods}} - end - - {{#hasAuthMethods}} - # Update hearder and query params based on authentication settings. - def update_params_for_auth! - (@auth_names || []).each do |auth_name| - case auth_name - {{#authMethods}}when '{{name}}' - {{#isApiKey}}{{#isKeyInHeader}}@headers ||= {} - @headers['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInHeader}}{{#isKeyInQuery}}@params ||= {} - @params['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}@headers ||= {} - http_auth_header = 'Basic ' + ["#{@api_client.username}:#{@api_client.password}"].pack('m').delete("\r\n") - @headers['Authorization'] = http_auth_header{{/isBasic}}{{#isOAuth}}# TODO: support oauth{{/isOAuth}} - {{/authMethods}} - end - end - end - {{/hasAuthMethods}} - - # Get API key (with prefix if set). - # @param [String] param_name the parameter name of API key auth - def get_api_key_with_prefix(param_name) - if @api_client.api_key_prefix[param_name] - "#{@api_client.api_key_prefix[param_name]} #{@api_client.api_key[param_name]}" - else - @api_client.api_key[param_name] - end - end - - # Construct the request URL. - def url(options = {}) - _path = self.interpreted_path - _path = "/#{_path}" unless _path.start_with?('/') - "#{@api_client.scheme}://#{@api_client.host}#{_path}" - end - - # Iterate over the params hash, injecting any path values into the path string - # e.g. /word.{format}/{word}/entries => /word.json/cat/entries - def interpreted_path - p = self.path.dup - - # Stick a .{format} placeholder into the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words.{format}/blah - if @api_client.inject_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = p.sub(/^(\/?\w+)/, "\\1.#{format}") - end - end - - # Stick a .{format} placeholder on the end of the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words/blah.{format} - if @api_client.force_ending_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = "#{p}.#{format}" - end - end - - p = p.sub("{format}", self.format.to_s) - - URI.encode [@api_client.base_path, p].join("/").gsub(/\/+/, '/') - end - - # If body is an object, JSONify it before making the actual request. - # For form parameters, remove empty value - def outgoing_body - # http form - if headers['Content-Type'] == 'application/x-www-form-urlencoded' - data = form_params.dup - data.each do |key, value| - data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter - end - elsif @body # http body is JSON - data = @body.is_a?(String) ? @body : @body.to_json - else - data = nil - end - - if @api_client.debugging - @api_client.logger.debug "HTTP request body param ~BEGIN~\n#{data}\n~END~\n" - end - - data - end - - def make - request_options = { - :method => self.http_method, - :headers => self.headers, - :params => self.params, - :ssl_verifypeer => @api_client.verify_ssl, - :cainfo => @api_client.ssl_ca_cert, - :verbose => @api_client.debugging - } - - if [:post, :patch, :put, :delete].include?(self.http_method) - request_options.update :body => self.outgoing_body - end - - raw = Typhoeus::Request.new(self.url, request_options).run - @response = Response.new(@api_client, raw) - - if @api_client.debugging - @api_client.logger.debug "HTTP response body ~BEGIN~\n#{@response.body}\n~END~\n" - end - - # record as last response - @api_client.last_response = @response - - unless @response.success? - fail ApiError.new(:code => @response.code, - :response_headers => @response.headers, - :response_body => @response.body), - @response.status_message - end - - @response - end - - def response_code_pretty - return unless @response - @response.code.to_s - end - - def response_headers_pretty - return unless @response - # JSON.pretty_generate(@response.headers).gsub(/\n/, '
') # <- This was for RestClient - @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus - end - - # return 'Accept' based on an array of accept provided - # @param [Array] header_accept_array Array fo 'Accept' - # @return String Accept (e.g. application/json) - def self.select_header_accept header_accept_array - if header_accept_array.empty? - return - elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # look for json data by default - else - header_accept_array.join(',') - end - end - - # return the content type based on an array of content-type provided - # @param [Array] content_type_array Array fo content-type - # @return String Content-Type (e.g. application/json) - def self.select_header_content_type content_type_array - if content_type_array.empty? - 'application/json' # use application/json by default - elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # use application/json if it's included - else - content_type_array[0]; # otherwise, use the first one - end - end - - # static method to convert object (array, hash, object, etc) to JSON string - # @param model object to be converted into JSON string - # @return string JSON string representation of the object - def self.object_to_http_body model - return if model.nil? - _body = nil - if model.is_a?(Array) - _body = model.map{|m| object_to_hash(m) } - else - _body = object_to_hash(model) - end - _body.to_json - end - - # static method to convert object(non-array) to hash - # @param obj object to be converted into JSON string - # @return string JSON string representation of the object - def self.object_to_hash obj - if obj.respond_to?(:to_hash) - obj.to_hash - else - obj - end - end - end -end diff --git a/modules/swagger-codegen/src/main/resources/ruby/response.mustache b/modules/swagger-codegen/src/main/resources/ruby/response.mustache deleted file mode 100644 index d3119437232..00000000000 --- a/modules/swagger-codegen/src/main/resources/ruby/response.mustache +++ /dev/null @@ -1,155 +0,0 @@ -require 'json' -require 'date' -require 'tempfile' - -module {{moduleName}} - class Response - attr_accessor :raw - - def initialize(api_client, raw) - @api_client = api_client - @raw = raw - end - - def code - raw.code - end - - def status_message - raw.status_message - end - - def body - raw.body - end - - def success? - raw.success? - end - - # Deserialize the raw response body to the given return type. - # - # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]" - def deserialize(return_type) - return nil if body.nil? || body.empty? - - # handle file downloading - save response body into a tmp file and return the File instance - return download_file if return_type == 'File' - - # ensuring a default content type - content_type = raw.headers['Content-Type'] || 'application/json' - - unless content_type.start_with?('application/json') - fail "Content-Type is not supported: #{content_type}" - end - - begin - data = JSON.parse("[#{body}]", :symbolize_names => true)[0] - rescue JSON::ParserError => e - if %w(String Date DateTime).include?(return_type) - data = body - else - raise e - end - end - - convert_to_type data, return_type - end - - # Convert data to the given return type. - def convert_to_type(data, return_type) - return nil if data.nil? - case return_type - 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 - when 'Date' - # parse date time (expecting ISO 8601 format) - Date.parse data - when 'Object' - # generic object, return directly - data - when /\AArray<(.+)>\z/ - # e.g. Array - sub_type = $1 - data.map {|item| convert_to_type(item, sub_type) } - when /\AHash\\z/ - # e.g. Hash - sub_type = $1 - {}.tap do |hash| - data.each {|k, v| hash[k] = convert_to_type(v, sub_type) } - end - else - # models, e.g. Pet - {{moduleName}}.const_get(return_type).new.tap do |model| - model.build_from_hash data - end - end - end - - # Save response body into a file in (the defined) temporary folder, using the filename - # from the "Content-Disposition" header if provided, otherwise a random filename. - # - # @see Configuration#temp_folder_path - # @return [File] the file downloaded - def download_file - tmp_file = Tempfile.new '', @api_client.temp_folder_path - content_disposition = raw.headers['Content-Disposition'] - if content_disposition - filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] - path = File.join File.dirname(tmp_file), filename - else - path = tmp_file.path - end - # close and delete temp file - tmp_file.close! - - File.open(path, 'w') { |file| file.write(raw.body) } - @api_client.logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards" - return File.new(path) - end - - # `headers_hash` is a Typhoeus-specific extension of Hash, - # so simplify it back into a regular old Hash. - def headers - h = {} - raw.headers_hash.each {|k,v| h[k] = v } - h - end - - # Extract the response format from the header hash - # e.g. {'Content-Type' => 'application/json'} - def format - headers['Content-Type'].split("/").last.downcase - end - - def json? - format == 'json' - end - - def xml? - format == 'xml' - end - - def pretty_body - return unless body - if format == 'json' - JSON.pretty_generate(JSON.parse(body)).gsub(/\n/, '
') - else - body - end - end - - def pretty_headers - JSON.pretty_generate(headers).gsub(/\n/, '
') - end - end -end From 7af5db35659fbb0f9ed44e217e9318f08617770d Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 27 Jul 2015 16:37:26 +0800 Subject: [PATCH 08/17] Rebuild Ruby petstore sample --- samples/client/petstore/ruby/lib/petstore.rb | 2 - .../petstore/ruby/lib/petstore/api/pet_api.rb | 114 +++++--- .../ruby/lib/petstore/api/store_api.rb | 60 ++-- .../ruby/lib/petstore/api/user_api.rb | 116 +++++--- .../petstore/ruby/lib/petstore/api_client.rb | 256 +++++++++++++++++- .../petstore/ruby/lib/petstore/request.rb | 207 -------------- .../petstore/ruby/lib/petstore/response.rb | 155 ----------- .../petstore/ruby/spec/api_client_spec.rb | 51 ++++ .../client/petstore/ruby/spec/request_spec.rb | 113 -------- .../petstore/ruby/spec/response_spec.rb | 77 ------ 10 files changed, 499 insertions(+), 652 deletions(-) delete mode 100644 samples/client/petstore/ruby/lib/petstore/request.rb delete mode 100644 samples/client/petstore/ruby/lib/petstore/response.rb delete mode 100644 samples/client/petstore/ruby/spec/request_spec.rb delete mode 100644 samples/client/petstore/ruby/spec/response_spec.rb diff --git a/samples/client/petstore/ruby/lib/petstore.rb b/samples/client/petstore/ruby/lib/petstore.rb index f77710df1ea..9fa3a39f5f7 100644 --- a/samples/client/petstore/ruby/lib/petstore.rb +++ b/samples/client/petstore/ruby/lib/petstore.rb @@ -1,8 +1,6 @@ # Common files require 'petstore/api_client' require 'petstore/api_error' -require 'petstore/request' -require 'petstore/response' require 'petstore/version' # Models diff --git a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb index 419aec9f044..5f21e703fb6 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb @@ -30,25 +30,30 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = ['application/json', 'application/xml'] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Request.object_to_http_body(opts[:'body']) + post_body = @api_client.object_to_http_body(opts[:'body']) auth_names = ['petstore_auth'] - Request.new(@api_client, :PUT, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + @api_client.call_api(:PUT, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) if @api_client.debugging @api_client.logger.debug "API called: PetApi#update_pet" end - nil + return nil end # Add a new pet to the store @@ -72,25 +77,30 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = ['application/json', 'application/xml'] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Request.object_to_http_body(opts[:'body']) + post_body = @api_client.object_to_http_body(opts[:'body']) auth_names = ['petstore_auth'] - Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + @api_client.call_api(:POST, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) if @api_client.debugging @api_client.logger.debug "API called: PetApi#add_pet" end - nil + return nil end # Finds Pets by status @@ -115,11 +125,11 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -129,12 +139,17 @@ module Petstore auth_names = ['petstore_auth'] - response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - result = response.deserialize('Array') + result = @api_client.call_api(:GET, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => 'Array') if @api_client.debugging @api_client.logger.debug "API called: PetApi#find_pets_by_status. Result: #{result.inspect}" end - result + return result end # Finds Pets by tags @@ -159,11 +174,11 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -173,12 +188,17 @@ module Petstore auth_names = ['petstore_auth'] - response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - result = response.deserialize('Array') + result = @api_client.call_api(:GET, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => 'Array') if @api_client.debugging @api_client.logger.debug "API called: PetApi#find_pets_by_tags. Result: #{result.inspect}" end - result + return result end # Find pet by ID @@ -205,11 +225,11 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -219,12 +239,17 @@ module Petstore auth_names = ['api_key', 'petstore_auth'] - response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - result = response.deserialize('Pet') + result = @api_client.call_api(:GET, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => 'Pet') if @api_client.debugging @api_client.logger.debug "API called: PetApi#get_pet_by_id. Result: #{result.inspect}" end - result + return result end # Updates a pet in the store with form data @@ -253,11 +278,11 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = ['application/x-www-form-urlencoded'] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -269,11 +294,16 @@ module Petstore auth_names = ['petstore_auth'] - Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + @api_client.call_api(:POST, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) if @api_client.debugging @api_client.logger.debug "API called: PetApi#update_pet_with_form" end - nil + return nil end # Deletes a pet @@ -301,11 +331,11 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) header_params[:'api_key'] = opts[:'api_key'] if opts[:'api_key'] # form parameters @@ -316,11 +346,16 @@ module Petstore auth_names = ['petstore_auth'] - Request.new(@api_client, :DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + @api_client.call_api(:DELETE, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) if @api_client.debugging @api_client.logger.debug "API called: PetApi#delete_pet" end - nil + return nil end # uploads an image @@ -349,11 +384,11 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = ['multipart/form-data'] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -365,11 +400,16 @@ module Petstore auth_names = ['petstore_auth'] - Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + @api_client.call_api(:POST, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) if @api_client.debugging @api_client.logger.debug "API called: PetApi#upload_file" end - nil + return nil end end end diff --git a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb index ada198f46a3..ec9f16001f2 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb @@ -29,11 +29,11 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -43,12 +43,17 @@ module Petstore auth_names = ['api_key'] - response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - result = response.deserialize('Hash') + result = @api_client.call_api(:GET, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => 'Hash') if @api_client.debugging @api_client.logger.debug "API called: StoreApi#get_inventory. Result: #{result.inspect}" end - result + return result end # Place an order for a pet @@ -72,26 +77,31 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Request.object_to_http_body(opts[:'body']) + post_body = @api_client.object_to_http_body(opts[:'body']) auth_names = [] - response = Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - result = response.deserialize('Order') + result = @api_client.call_api(:POST, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => 'Order') if @api_client.debugging @api_client.logger.debug "API called: StoreApi#place_order. Result: #{result.inspect}" end - result + return result end # Find purchase order by ID @@ -118,11 +128,11 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -132,12 +142,17 @@ module Petstore auth_names = [] - response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - result = response.deserialize('Order') + result = @api_client.call_api(:GET, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => 'Order') if @api_client.debugging @api_client.logger.debug "API called: StoreApi#get_order_by_id. Result: #{result.inspect}" end - result + return result end # Delete purchase order by ID @@ -164,11 +179,11 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -178,11 +193,16 @@ module Petstore auth_names = [] - Request.new(@api_client, :DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + @api_client.call_api(:DELETE, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) if @api_client.debugging @api_client.logger.debug "API called: StoreApi#delete_order" end - nil + return nil end end end diff --git a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb index 375baffc3ef..eda69c97282 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb @@ -30,25 +30,30 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Request.object_to_http_body(opts[:'body']) + post_body = @api_client.object_to_http_body(opts[:'body']) auth_names = [] - Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + @api_client.call_api(:POST, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) if @api_client.debugging @api_client.logger.debug "API called: UserApi#create_user" end - nil + return nil end # Creates list of users with given input array @@ -72,25 +77,30 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Request.object_to_http_body(opts[:'body']) + post_body = @api_client.object_to_http_body(opts[:'body']) auth_names = [] - Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + @api_client.call_api(:POST, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) if @api_client.debugging @api_client.logger.debug "API called: UserApi#create_users_with_array_input" end - nil + return nil end # Creates list of users with given input array @@ -114,25 +124,30 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Request.object_to_http_body(opts[:'body']) + post_body = @api_client.object_to_http_body(opts[:'body']) auth_names = [] - Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + @api_client.call_api(:POST, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) if @api_client.debugging @api_client.logger.debug "API called: UserApi#create_users_with_list_input" end - nil + return nil end # Logs user into the system @@ -159,11 +174,11 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -173,12 +188,17 @@ module Petstore auth_names = [] - response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - result = response.deserialize('String') + result = @api_client.call_api(:GET, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => 'String') if @api_client.debugging @api_client.logger.debug "API called: UserApi#login_user. Result: #{result.inspect}" end - result + return result end # Logs out current logged in user session @@ -201,11 +221,11 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -215,11 +235,16 @@ module Petstore auth_names = [] - Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + @api_client.call_api(:GET, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) if @api_client.debugging @api_client.logger.debug "API called: UserApi#logout_user" end - nil + return nil end # Get user by user name @@ -246,11 +271,11 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -260,12 +285,17 @@ module Petstore auth_names = [] - response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - result = response.deserialize('User') + result = @api_client.call_api(:GET, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => 'User') if @api_client.debugging @api_client.logger.debug "API called: UserApi#get_user_by_name. Result: #{result.inspect}" end - result + return result end # Updated user @@ -293,25 +323,30 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Request.object_to_http_body(opts[:'body']) + post_body = @api_client.object_to_http_body(opts[:'body']) auth_names = [] - Request.new(@api_client, :PUT, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + @api_client.call_api(:PUT, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) if @api_client.debugging @api_client.logger.debug "API called: UserApi#update_user" end - nil + return nil end # Delete user @@ -338,11 +373,11 @@ module Petstore # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -352,11 +387,16 @@ module Petstore auth_names = [] - Request.new(@api_client, :DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + @api_client.call_api(:DELETE, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) if @api_client.debugging @api_client.logger.debug "API called: UserApi#delete_user" end - nil + return nil end end end diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index 2f4b76d5422..6d4dda8f939 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -1,9 +1,13 @@ -require 'logger' +require 'date' require 'json' +require 'logger' +require 'tempfile' +require 'typhoeus' +require 'uri' module Petstore class ApiClient - attr_accessor :scheme, :host, :base_path, :user_agent, :format, :auth_token, :inject_format, :force_ending_format + attr_accessor :scheme, :host, :base_path, :user_agent # Defines the username used with HTTP basic authentication. # @@ -82,7 +86,6 @@ module Petstore # client.api_key['api_key'] = 'your key' # api key authentication # client.username = 'your username' # username for http basic authentication # client.password = 'your password' # password for http basic authentication - # client.format = 'json' # optional, defaults to 'json' # end def initialize(&block) @format = 'json' @@ -131,9 +134,256 @@ module Petstore @base_path = "" if @base_path == "/" end + def call_api(http_method, path, opts = {}) + request = build_request(http_method, path, opts) + response = request.run + + # record as last response + @last_response = response + + if debugging + logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" + end + + unless response.success? + fail ApiError.new(:code => response.code, + :response_headers => response.headers, + :response_body => response.body), + response.status_message + end + + if opts[:return_type] + return deserialize(response, opts[:return_type]) + else + return nil + end + end + + def build_request(http_method, path, opts = {}) + url = build_request_url(path) + http_method = http_method.to_sym.downcase + + header_params = @default_headers.merge(opts[:header_params] || {}) + query_params = opts[:query_params] || {} + form_params = opts[:form_params] || {} + + + update_params_for_auth! header_params, query_params, opts[:auth_names] + + + req_opts = { + :method => http_method, + :headers => header_params, + :params => query_params, + :ssl_verifypeer => @verify_ssl, + :cainfo => @ssl_ca_cert, + :verbose => @debugging + } + + if [:post, :patch, :put, :delete].include?(http_method) + req_body = build_request_body(header_params, form_params, opts[:body]) + req_opts.update :body => req_body + if debugging + logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n" + end + end + + Typhoeus::Request.new(url, req_opts) + end + + # Deserialize the response to the given return type. + # + # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]" + def deserialize(response, return_type) + body = response.body + return nil if body.nil? || body.empty? + + # handle file downloading - save response body into a tmp file and return the File instance + return download_file(response) if return_type == 'File' + + # ensuring a default content type + content_type = response.headers['Content-Type'] || 'application/json' + + unless content_type.start_with?('application/json') + fail "Content-Type is not supported: #{content_type}" + end + + begin + data = JSON.parse("[#{body}]", :symbolize_names => true)[0] + rescue JSON::ParserError => e + if %w(String Date DateTime).include?(return_type) + data = body + else + raise e + end + end + + convert_to_type data, return_type + end + + # Convert data to the given return type. + def convert_to_type(data, return_type) + return nil if data.nil? + case return_type + 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 + when 'Date' + # parse date time (expecting ISO 8601 format) + Date.parse data + when 'Object' + # generic object, return directly + data + when /\AArray<(.+)>\z/ + # e.g. Array + sub_type = $1 + data.map {|item| convert_to_type(item, sub_type) } + when /\AHash\\z/ + # e.g. Hash + sub_type = $1 + {}.tap do |hash| + data.each {|k, v| hash[k] = convert_to_type(v, sub_type) } + end + else + # models, e.g. Pet + Petstore.const_get(return_type).new.tap do |model| + model.build_from_hash data + end + end + end + + # Save response body into a file in (the defined) temporary folder, using the filename + # from the "Content-Disposition" header if provided, otherwise a random filename. + # + # @see Configuration#temp_folder_path + # @return [File] the file downloaded + def download_file(response) + tmp_file = Tempfile.new '', @temp_folder_path + content_disposition = response.headers['Content-Disposition'] + if content_disposition + filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] + path = File.join File.dirname(tmp_file), filename + else + path = tmp_file.path + end + # close and delete temp file + tmp_file.close! + + File.open(path, 'w') { |file| file.write(response.body) } + logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards" + return File.new(path) + end + + def build_request_url(path) + url = [host, base_path, path].join('/').gsub(/\/+/, '/') + url = "#{scheme}://#{url}" + URI.encode(url) + end + + def build_request_body(header_params, form_params, body) + # http form + if header_params['Content-Type'] == 'application/x-www-form-urlencoded' + data = form_params.dup + data.each do |key, value| + data[key] = value.to_s if value && !value.is_a?(File) + end + elsif body + data = body.is_a?(String) ? body : body.to_json + else + data = nil + end + return data + end + + + # Update hearder and query params based on authentication settings. + def update_params_for_auth!(header_params, query_params, auth_names) + return unless auth_names + auth_names.each do |auth_name| + case auth_name + when 'api_key' + header_params ||= {} + header_params['api_key'] = get_api_key_with_prefix('api_key') + when 'petstore_auth' + # TODO: support oauth + + end + end + end + + # Get API key (with prefix if set). + # @param [String] param_name the parameter name of API key auth + def get_api_key_with_prefix(param_name) + if @api_key_prefix[param_name] + "#{@api_key_prefix[param_name]} #{@api_key[param_name]}" + else + @api_key[param_name] + end + end + + def user_agent=(user_agent) @user_agent = user_agent @default_headers['User-Agent'] = @user_agent end + + # Return Accept header based on an array of accepts provided. + # @param [Array] accepts array for Accept + # @return [String] the Accept header (e.g. application/json) + def select_header_accept(accepts) + if accepts.empty? + return + elsif accepts.any?{ |s| s.casecmp('application/json') == 0 } + 'application/json' # look for json data by default + else + accepts.join(',') + end + end + + # Return Content-Type header based on an array of content types provided. + # @param [Array] content_types array for Content-Type + # @return [String] the Content-Type header (e.g. application/json) + def select_header_content_type(content_types) + if content_types.empty? + 'application/json' # use application/json by default + elsif content_types.any?{ |s| s.casecmp('application/json')==0 } + 'application/json' # use application/json if it's included + else + content_types[0] # otherwise, use the first one + end + end + + # Convert object (array, hash, object, etc) to JSON string. + # @param [Object] model object to be converted into JSON string + # @return [String] JSON string representation of the object + def object_to_http_body(model) + return if model.nil? + _body = nil + if model.is_a?(Array) + _body = model.map{|m| object_to_hash(m) } + else + _body = object_to_hash(model) + end + _body.to_json + end + + # Convert object(non-array) to hash. + # @param [Object] obj object to be converted into JSON string + # @return [String] JSON string representation of the object + def object_to_hash(obj) + if obj.respond_to?(:to_hash) + obj.to_hash + else + obj + end + end end end diff --git a/samples/client/petstore/ruby/lib/petstore/request.rb b/samples/client/petstore/ruby/lib/petstore/request.rb deleted file mode 100644 index af884537ff8..00000000000 --- a/samples/client/petstore/ruby/lib/petstore/request.rb +++ /dev/null @@ -1,207 +0,0 @@ -require 'uri' -require 'typhoeus' - -module Petstore - class Request - attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params, :auth_names, :response - - # All requests must have an HTTP method and a path - # Optionals parameters are :params, :headers, :body, :format, :host - def initialize(api_client, http_method, path, attributes = {}) - @api_client = api_client - - @http_method = http_method.to_sym.downcase - @path = path - - attributes.each { |name, value| send "#{name}=", value } - - @format ||= @api_client.format - @params ||= {} - - # Apply default headers - @headers = @api_client.default_headers.merge(@headers || {}) - - update_params_for_auth! - - end - - - # Update hearder and query params based on authentication settings. - def update_params_for_auth! - (@auth_names || []).each do |auth_name| - case auth_name - when 'api_key' - @headers ||= {} - @headers['api_key'] = get_api_key_with_prefix('api_key') - when 'petstore_auth' - # TODO: support oauth - - end - end - end - - - # Get API key (with prefix if set). - # @param [String] param_name the parameter name of API key auth - def get_api_key_with_prefix(param_name) - if @api_client.api_key_prefix[param_name] - "#{@api_client.api_key_prefix[param_name]} #{@api_client.api_key[param_name]}" - else - @api_client.api_key[param_name] - end - end - - # Construct the request URL. - def url(options = {}) - _path = self.interpreted_path - _path = "/#{_path}" unless _path.start_with?('/') - "#{@api_client.scheme}://#{@api_client.host}#{_path}" - end - - # Iterate over the params hash, injecting any path values into the path string - # e.g. /word.{format}/{word}/entries => /word.json/cat/entries - def interpreted_path - p = self.path.dup - - # Stick a .{format} placeholder into the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words.{format}/blah - if @api_client.inject_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = p.sub(/^(\/?\w+)/, "\\1.#{format}") - end - end - - # Stick a .{format} placeholder on the end of the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words/blah.{format} - if @api_client.force_ending_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = "#{p}.#{format}" - end - end - - p = p.sub("{format}", self.format.to_s) - - URI.encode [@api_client.base_path, p].join("/").gsub(/\/+/, '/') - end - - # If body is an object, JSONify it before making the actual request. - # For form parameters, remove empty value - def outgoing_body - # http form - if headers['Content-Type'] == 'application/x-www-form-urlencoded' - data = form_params.dup - data.each do |key, value| - data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter - end - elsif @body # http body is JSON - data = @body.is_a?(String) ? @body : @body.to_json - else - data = nil - end - - if @api_client.debugging - @api_client.logger.debug "HTTP request body param ~BEGIN~\n#{data}\n~END~\n" - end - - data - end - - def make - request_options = { - :method => self.http_method, - :headers => self.headers, - :params => self.params, - :ssl_verifypeer => @api_client.verify_ssl, - :cainfo => @api_client.ssl_ca_cert, - :verbose => @api_client.debugging - } - - if [:post, :patch, :put, :delete].include?(self.http_method) - request_options.update :body => self.outgoing_body - end - - raw = Typhoeus::Request.new(self.url, request_options).run - @response = Response.new(@api_client, raw) - - if @api_client.debugging - @api_client.logger.debug "HTTP response body ~BEGIN~\n#{@response.body}\n~END~\n" - end - - # record as last response - @api_client.last_response = @response - - unless @response.success? - fail ApiError.new(:code => @response.code, - :response_headers => @response.headers, - :response_body => @response.body), - @response.status_message - end - - @response - end - - def response_code_pretty - return unless @response - @response.code.to_s - end - - def response_headers_pretty - return unless @response - # JSON.pretty_generate(@response.headers).gsub(/\n/, '
') # <- This was for RestClient - @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus - end - - # return 'Accept' based on an array of accept provided - # @param [Array] header_accept_array Array fo 'Accept' - # @return String Accept (e.g. application/json) - def self.select_header_accept header_accept_array - if header_accept_array.empty? - return - elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # look for json data by default - else - header_accept_array.join(',') - end - end - - # return the content type based on an array of content-type provided - # @param [Array] content_type_array Array fo content-type - # @return String Content-Type (e.g. application/json) - def self.select_header_content_type content_type_array - if content_type_array.empty? - 'application/json' # use application/json by default - elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # use application/json if it's included - else - content_type_array[0]; # otherwise, use the first one - end - end - - # static method to convert object (array, hash, object, etc) to JSON string - # @param model object to be converted into JSON string - # @return string JSON string representation of the object - def self.object_to_http_body model - return if model.nil? - _body = nil - if model.is_a?(Array) - _body = model.map{|m| object_to_hash(m) } - else - _body = object_to_hash(model) - end - _body.to_json - end - - # static method to convert object(non-array) to hash - # @param obj object to be converted into JSON string - # @return string JSON string representation of the object - def self.object_to_hash obj - if obj.respond_to?(:to_hash) - obj.to_hash - else - obj - end - end - end -end diff --git a/samples/client/petstore/ruby/lib/petstore/response.rb b/samples/client/petstore/ruby/lib/petstore/response.rb deleted file mode 100644 index e54e13ac951..00000000000 --- a/samples/client/petstore/ruby/lib/petstore/response.rb +++ /dev/null @@ -1,155 +0,0 @@ -require 'json' -require 'date' -require 'tempfile' - -module Petstore - class Response - attr_accessor :raw - - def initialize(api_client, raw) - @api_client = api_client - @raw = raw - end - - def code - raw.code - end - - def status_message - raw.status_message - end - - def body - raw.body - end - - def success? - raw.success? - end - - # Deserialize the raw response body to the given return type. - # - # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]" - def deserialize(return_type) - return nil if body.nil? || body.empty? - - # handle file downloading - save response body into a tmp file and return the File instance - return download_file if return_type == 'File' - - # ensuring a default content type - content_type = raw.headers['Content-Type'] || 'application/json' - - unless content_type.start_with?('application/json') - fail "Content-Type is not supported: #{content_type}" - end - - begin - data = JSON.parse("[#{body}]", :symbolize_names => true)[0] - rescue JSON::ParserError => e - if %w(String Date DateTime).include?(return_type) - data = body - else - raise e - end - end - - convert_to_type data, return_type - end - - # Convert data to the given return type. - def convert_to_type(data, return_type) - return nil if data.nil? - case return_type - 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 - when 'Date' - # parse date time (expecting ISO 8601 format) - Date.parse data - when 'Object' - # generic object, return directly - data - when /\AArray<(.+)>\z/ - # e.g. Array - sub_type = $1 - data.map {|item| convert_to_type(item, sub_type) } - when /\AHash\\z/ - # e.g. Hash - sub_type = $1 - {}.tap do |hash| - data.each {|k, v| hash[k] = convert_to_type(v, sub_type) } - end - else - # models, e.g. Pet - Petstore.const_get(return_type).new.tap do |model| - model.build_from_hash data - end - end - end - - # Save response body into a file in (the defined) temporary folder, using the filename - # from the "Content-Disposition" header if provided, otherwise a random filename. - # - # @see Configuration#temp_folder_path - # @return [File] the file downloaded - def download_file - tmp_file = Tempfile.new '', @api_client.temp_folder_path - content_disposition = raw.headers['Content-Disposition'] - if content_disposition - filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] - path = File.join File.dirname(tmp_file), filename - else - path = tmp_file.path - end - # close and delete temp file - tmp_file.close! - - File.open(path, 'w') { |file| file.write(raw.body) } - @api_client.logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards" - return File.new(path) - end - - # `headers_hash` is a Typhoeus-specific extension of Hash, - # so simplify it back into a regular old Hash. - def headers - h = {} - raw.headers_hash.each {|k,v| h[k] = v } - h - end - - # Extract the response format from the header hash - # e.g. {'Content-Type' => 'application/json'} - def format - headers['Content-Type'].split("/").last.downcase - end - - def json? - format == 'json' - end - - def xml? - format == 'xml' - end - - def pretty_body - return unless body - if format == 'json' - JSON.pretty_generate(JSON.parse(body)).gsub(/\n/, '
') - else - body - end - end - - def pretty_headers - JSON.pretty_generate(headers).gsub(/\n/, '
') - end - end -end diff --git a/samples/client/petstore/ruby/spec/api_client_spec.rb b/samples/client/petstore/ruby/spec/api_client_spec.rb index f66dcdd68fd..69c4490c960 100644 --- a/samples/client/petstore/ruby/spec/api_client_spec.rb +++ b/samples/client/petstore/ruby/spec/api_client_spec.rb @@ -50,4 +50,55 @@ describe Petstore::ApiClient do end + describe "#update_params_for_auth!" do + it "sets header api-key parameter with prefix" do + api_client = Petstore::ApiClient.new do |c| + c.api_key_prefix['api_key'] = 'PREFIX' + c.api_key['api_key'] = 'special-key' + end + header_params = {} + query_params = {} + auth_names = ['api_key', 'unknown'] + api_client.update_params_for_auth! header_params, query_params, auth_names + header_params.should == {'api_key' => 'PREFIX special-key'} + query_params.should == {} + end + + it "sets header api-key parameter without prefix" do + api_client = Petstore::ApiClient.new do |c| + c.api_key_prefix['api_key'] = nil + c.api_key['api_key'] = 'special-key' + end + header_params = {} + query_params = {} + auth_names = ['api_key', 'unknown'] + api_client.update_params_for_auth! header_params, query_params, auth_names + header_params.should == {'api_key' => 'special-key'} + query_params.should == {} + end + end + + describe "#deserialize" do + it "handles Hash" do + api_client = Petstore::ApiClient.new + headers = {'Content-Type' => 'application/json'} + response = double('response', headers: headers, body: '{"message": "Hello"}') + data = api_client.deserialize(response, 'Hash') + data.should be_a(Hash) + data.should == {:message => 'Hello'} + end + + it "handles Hash" do + api_client = Petstore::ApiClient.new + headers = {'Content-Type' => 'application/json'} + response = double('response', headers: headers, body: '{"pet": {"id": 1}}') + data = api_client.deserialize(response, 'Hash') + data.should be_a(Hash) + data.keys.should == [:pet] + pet = data[:pet] + pet.should be_a(Petstore::Pet) + pet.id.should == 1 + end + end + end diff --git a/samples/client/petstore/ruby/spec/request_spec.rb b/samples/client/petstore/ruby/spec/request_spec.rb deleted file mode 100644 index b4bf64c8f39..00000000000 --- a/samples/client/petstore/ruby/spec/request_spec.rb +++ /dev/null @@ -1,113 +0,0 @@ -require 'spec_helper' - -describe Petstore::Request do - - before(:each) do - @api_client = Petstore::ApiClient.new do |config| - inject_format = true - config.api_key['api_key'] = 'special-key' - config.host = 'petstore.swagger.io' - config.base_path = '/v2' - end - - @default_http_method = :get - @default_path = "pet.{format}/fancy" - @default_params = { - :params => {:foo => "1", :bar => "2"} - } - @request = Petstore::Request.new(@api_client, @default_http_method, @default_path, @default_params) - end - - describe "initialization" do - - it "sets default response format to json" do - @request.format.should == 'json' - end - - it "sets default headers correctly" do - @request.headers.should == {'Content-Type' => 'application/json', 'User-Agent' => 'ruby-swagger-1.0.0'} - end - - it "allows params to be nil" do - @request = Petstore::Request.new(@api_client, @default_http_method, @default_path, :params => nil) - @request.params.should == {} - end - - end - - describe "attr_accessors" do - - it "has working attributes" do - @request.format.to_s.should == 'json' - end - - it "allows attributes to be overwritten" do - @request.http_method.should == :get - @request.http_method = "post" - @request.http_method.should == 'post' - end - - end - - describe "url" do - - it "constructs a full url" do - @request.url.should == "http://petstore.swagger.io/v2/pet.json/fancy" - end - - end - - describe "path" do - - it "accounts for a total absence of format in the path string" do - @request = Petstore::Request.new(@api_client, :get, "/word.{format}/cat/entries", @default_params.merge({ - :format => "xml", - :params => { - } - })) - @request.url.should == "http://petstore.swagger.io/v2/word.xml/cat/entries" - end - - it "does string substitution (format) on path params" do - @request = Petstore::Request.new(@api_client, :get, "/word.{format}/cat/entries", @default_params.merge({ - :format => "xml", - :params => { - } - })) - @request.url.should == "http://petstore.swagger.io/v2/word.xml/cat/entries" - end - - it "URI encodes the path" do - @request = Petstore::Request.new(@api_client, :get, "word.{format}/bill gates/definitions", @default_params.merge({ - :params => { - :word => "bill gates" - } - })) - @request.url.should =~ /word.json\/bill\%20gates\/definitions/ - end - - end - - describe "#update_params_for_auth!" do - it "sets header api-key parameter with prefix" do - @api_client.configure do |config| - inject_format = true - config.api_key_prefix['api_key'] = 'PREFIX' - end - @request.auth_names = ['api_key', 'unknown'] - @request.update_params_for_auth! - @request.headers['api_key'].should == 'PREFIX special-key' - end - - it "sets header api-key parameter without prefix" do - @api_client.configure do |config| - inject_format = true - config.api_key_prefix['api_key'] = nil - end - @request.auth_names = ['api_key', 'unknown'] - @request.update_params_for_auth! - @request.headers['api_key'].should == 'special-key' - end - end - -end diff --git a/samples/client/petstore/ruby/spec/response_spec.rb b/samples/client/petstore/ruby/spec/response_spec.rb deleted file mode 100644 index 4aeea0ea832..00000000000 --- a/samples/client/petstore/ruby/spec/response_spec.rb +++ /dev/null @@ -1,77 +0,0 @@ -require 'spec_helper' - -describe Petstore::Response do - - before(:each) do - VCR.use_cassette('pet_resource', :record => :new_episodes) do - @raw = Typhoeus::Request.get("http://petstore.swagger.io/v2/pet/10002") - end - - @response = Petstore::Response.new(API_CLIENT, @raw) - end - - describe "initialization" do - it "sets body" do - @response.body.should be_a(String) - data = JSON.parse(@response.body) - data.should be_a(Hash) - data['id'].should == 10002 - end - - it "sets code" do - @response.code.should == 200 - end - - it "converts header string into a hash" do - @response.headers.class.should == Hash - end - end - - describe "format" do - it "recognizes json" do - @response.format.should == 'json' - @response.json?.should == true - end - - it "recognizes xml" do - VCR.use_cassette('xml_response_request', :record => :new_episodes) do - @raw = Typhoeus::Request.get("http://petstore.swagger.io/v2/pet/10002", - :headers => {'Accept'=> "application/xml"}) - end - @response = Petstore::Response.new(API_CLIENT, @raw) - @response.format.should == 'xml' - @response.xml?.should == true - end - end - - describe "prettiness" do - it "has a pretty json body" do - @response.pretty_body.should =~ /\{.*\}/ - end - - it "has pretty headers" do - @response.pretty_headers.should =~ /\{.*\}/ - end - end - - describe "deserialize" do - it "handles Hash" do - @response.stub(:body) { '{"message": "Hello"}' } - data = @response.deserialize('Hash') - data.should be_a(Hash) - data.should == {:message => 'Hello'} - end - - it "handles Hash" do - json = @response.body - @response.stub(:body) { "{\"pet\": #{json}}" } - data = @response.deserialize('Hash') - data.should be_a(Hash) - data.keys.should == [:pet] - pet = data[:pet] - pet.should be_a(Petstore::Pet) - pet.id.should == 10002 - end - end - -end From a481db7486dacecb9e2251b55a62cdb0dfca9270 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Fri, 14 Aug 2015 16:19:43 +0800 Subject: [PATCH 09/17] Add configuration object in ruby client --- .../codegen/languages/RubyClientCodegen.java | 1 + .../src/main/resources/ruby/api.mustache | 19 +- .../main/resources/ruby/api_client.mustache | 161 +++------------- .../resources/ruby/configuration.mustache | 177 ++++++++++++++++++ .../src/main/resources/ruby/gem.mustache | 16 ++ samples/client/petstore/ruby/lib/petstore.rb | 16 ++ .../petstore/ruby/lib/petstore/api/pet_api.rb | 71 +++---- .../ruby/lib/petstore/api/store_api.rb | 39 ++-- .../ruby/lib/petstore/api/user_api.rb | 71 +++---- .../petstore/ruby/lib/petstore/api_client.rb | 162 +++------------- .../ruby/lib/petstore/configuration.rb | 164 ++++++++++++++++ .../petstore/ruby/spec/api_client_spec.rb | 39 ++-- 12 files changed, 542 insertions(+), 394 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/ruby/configuration.mustache create mode 100644 samples/client/petstore/ruby/lib/petstore/configuration.rb diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java index c82b5f7b6ce..61fcd8240b5 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java @@ -110,6 +110,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { String gemFolder = libFolder + File.separator + gemName; supportingFiles.add(new SupportingFile("api_client.mustache", gemFolder, "api_client.rb")); supportingFiles.add(new SupportingFile("api_error.mustache", gemFolder, "api_error.rb")); + supportingFiles.add(new SupportingFile("configuration.mustache", gemFolder, "configuration.rb")); supportingFiles.add(new SupportingFile("version.mustache", gemFolder, "version.rb")); String modelFolder = gemFolder + File.separator + modelPackage.replace("/", File.separator); supportingFiles.add(new SupportingFile("base_object.mustache", modelFolder, "base_object.rb")); diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index e1a6789c54f..ad885dac94e 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -6,9 +6,8 @@ module {{moduleName}} attr_accessor :api_client def initialize(api_client = nil) - @api_client = api_client || ApiClient.default + @api_client = api_client || Configuration.api_client end - {{#operation}} {{newline}} # {{summary}} @@ -18,8 +17,8 @@ module {{moduleName}} {{#allParams}}{{^required}} # @option opts [{{{dataType}}}] :{{paramName}} {{description}} {{/required}}{{/allParams}} # @return [{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}] def {{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: {{classname}}#{{nickname}} ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: {{classname}}#{{nickname}} ..." end {{#allParams}}{{#required}} # verify the required parameter '{{paramName}}' is set @@ -71,8 +70,8 @@ module {{moduleName}} :body => post_body, :auth_names => auth_names, :return_type => '{{{returnType}}}') - if @api_client.debugging - @api_client.logger.debug "API called: {{classname}}#{{nickname}}. Result: #{result.inspect}" + if Configuration.debugging + Configuration.logger.debug "API called: {{classname}}#{{nickname}}. Result: #{result.inspect}" end return result{{/returnType}}{{^returnType}}@api_client.call_api(:{{httpMethod}}, path, :header_params => header_params, @@ -80,8 +79,8 @@ module {{moduleName}} :form_params => form_params, :body => post_body, :auth_names => auth_names) - if @api_client.debugging - @api_client.logger.debug "API called: {{classname}}#{{nickname}}" + if Configuration.debugging + Configuration.logger.debug "API called: {{classname}}#{{nickname}}" end return nil{{/returnType}} end @@ -89,3 +88,7 @@ module {{moduleName}} end {{/operations}} end + + + + diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache index e6cc8fac49a..6bc6df0430b 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache @@ -7,69 +7,8 @@ require 'uri' module {{moduleName}} class ApiClient - attr_accessor :scheme, :host, :base_path, :user_agent - # Defines the username used with HTTP basic authentication. - # - # @return [String] - attr_accessor :username - - # Defines the password used with HTTP basic authentication. - # - # @return [String] - attr_accessor :password - - # Defines API keys used with API Key authentications. - # - # @return [Hash] key: parameter name, value: parameter value (API key) - # - # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string) - # config.api_key['api_key'] = 'xxx' - attr_accessor :api_key - - # Defines API key prefixes used with API Key authentications. - # - # @return [Hash] key: parameter name, value: API key prefix - # - # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers) - # config.api_key_prefix['api_key'] = 'Token' - attr_accessor :api_key_prefix - - # Set this to false to skip verifying SSL certificate when calling API from https server. - # Default to true. - # - # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. - # - # @return [true, false] - attr_accessor :verify_ssl - - # Set this to customize the certificate file to verify the peer. - # - # @return [String] the path to the certificate file - # - # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code: - # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 - attr_accessor :ssl_ca_cert - - # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response - # details will be logged with `logger.debug` (see the `logger` attribute). - # Default to false. - # - # @return [true, false] - attr_accessor :debugging - - # Defines the logger used for debugging. - # Default to `Rails.logger` (when in Rails) or logging to STDOUT. - # - # @return [#debug] - attr_accessor :logger - - # Defines the temporary folder to store downloaded files - # (for API endpoints that have file response). - # Default to use `Tempfile`. - # - # @return [String] - attr_accessor :temp_folder_path + attr_accessor :host # Defines the headers to be used in HTTP requests of all API calls by default. # @@ -79,59 +18,14 @@ module {{moduleName}} # Stores the HTTP response from the last API call using this API client. attr_accessor :last_response - # The constructor accepts a optional block to configure the API client. - # - # @example - # {{moduleName}}::ApiClient.new do |client| - # client.api_key['api_key'] = 'your key' # api key authentication - # client.username = 'your username' # username for http basic authentication - # client.password = 'your password' # password for http basic authentication - # end - def initialize(&block) + def initialize(host = nil) + @host = host || Configuration.base_url @format = 'json' - @scheme = '{{scheme}}' - @host = '{{host}}' - @base_path = '{{contextPath}}' @user_agent = "ruby-swagger-#{VERSION}" - @inject_format = false - @force_ending_format = false - @default_headers = { 'Content-Type' => "application/#{@format.downcase}", 'User-Agent' => @user_agent } - - # keys for API key authentication (param-name => api-key) - @api_key = {} - @api_key_prefix = {} - - @verify_ssl = true - - @debugging = false - @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT) - - configure(&block) - end - - # Default API client. - def self.default - @@default ||= ApiClient.new - end - - # Call this method to modify defaults in your initializers. - def configure - yield(self) if block_given? - - # remove :// from scheme - @scheme.sub!(/:\/\//, '') - - # remove http(s):// and anything after a slash - @host.sub!(/https?:\/\//, '') - @host = @host.split('/').first - - # Add leading and trailing slashes to base_path - @base_path = "/#{@base_path}".gsub(/\/+/, '/') - @base_path = "" if @base_path == "/" end def call_api(http_method, path, opts = {}) @@ -141,8 +35,8 @@ module {{moduleName}} # record as last response @last_response = response - if debugging - logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" + if Configuration.debugging + Configuration.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" end unless response.success? @@ -153,9 +47,9 @@ module {{moduleName}} end if opts[:return_type] - return deserialize(response, opts[:return_type]) + deserialize(response, opts[:return_type]) else - return nil + nil end end @@ -183,8 +77,8 @@ module {{moduleName}} if [:post, :patch, :put, :delete].include?(http_method) req_body = build_request_body(header_params, form_params, opts[:body]) req_opts.update :body => req_body - if debugging - logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n" + if Configuration.debugging + Configuration.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n" end end @@ -279,13 +173,13 @@ module {{moduleName}} File.open(path, 'w') { |file| file.write(response.body) } logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards" - return File.new(path) + File.new(path) end def build_request_url(path) - url = [host, base_path, path].join('/').gsub(/\/+/, '/') - url = "#{scheme}://#{url}" - URI.encode(url) + # Add leading and trailing slashes to path + path = "/#{path}".gsub(/\/+/, '/') + URI.encode(host + path) end def build_request_body(header_params, form_params, body) @@ -300,35 +194,22 @@ module {{moduleName}} else data = nil end - return data + data end - {{#hasAuthMethods}} # Update hearder and query params based on authentication settings. def update_params_for_auth!(header_params, query_params, auth_names) - return unless auth_names - auth_names.each do |auth_name| - case auth_name - {{#authMethods}}when '{{name}}' - {{#isApiKey}}{{#isKeyInHeader}}header_params ||= {} - header_params['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInHeader}}{{#isKeyInQuery}}query_params['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}http_auth_header = 'Basic ' + ["#{@username}:#{@password}"].pack('m').delete("\r\n") - header_params['Authorization'] = http_auth_header{{/isBasic}}{{#isOAuth}}# TODO: support oauth{{/isOAuth}} - {{/authMethods}} + Array(auth_names).each do |auth_name| + auth_setting = Configuration.auth_settings[auth_name] + next unless auth_setting + case auth_setting[:in] + when 'header' then header_params[auth_setting[:key]] = auth_setting[:value] + when 'query' then query_params[auth_setting[:key]] = auth_settings[:value] + else fail ArgumentError, 'Authentication token must be in `query` of `header`' end end end - # Get API key (with prefix if set). - # @param [String] param_name the parameter name of API key auth - def get_api_key_with_prefix(param_name) - if @api_key_prefix[param_name] - "#{@api_key_prefix[param_name]} #{@api_key[param_name]}" - else - @api_key[param_name] - end - end - {{/hasAuthMethods}} - def user_agent=(user_agent) @user_agent = user_agent @default_headers['User-Agent'] = @user_agent diff --git a/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache b/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache new file mode 100644 index 00000000000..600f9b7bafb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache @@ -0,0 +1,177 @@ +require 'uri' +require 'singleton' + +module {{moduleName}} + class Configuration + + include Singleton + + # Default api client + attr_accessor :api_client + + # Defines url scheme + attr_accessor :scheme + + # Defines url host + attr_accessor :host + + # Defines url base path + attr_accessor :base_path + + # Defines API keys used with API Key authentications. + # + # @return [Hash] key: parameter name, value: parameter value (API key) + # + # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string) + # config.api_key['api_key'] = 'xxx' + attr_accessor :api_key + + # Defines API key prefixes used with API Key authentications. + # + # @return [Hash] key: parameter name, value: API key prefix + # + # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers) + # config.api_key_prefix['api_key'] = 'Token' + attr_accessor :api_key_prefix + + # Defines the username used with HTTP basic authentication. + # + # @return [String] + attr_accessor :username + + # Defines the password used with HTTP basic authentication. + # + # @return [String] + attr_accessor :password + + # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response + # details will be logged with `logger.debug` (see the `logger` attribute). + # Default to false. + # + # @return [true, false] + attr_accessor :debugging + + # Defines the logger used for debugging. + # Default to `Rails.logger` (when in Rails) or logging to STDOUT. + # + # @return [#debug] + attr_accessor :logger + + # Defines the temporary folder to store downloaded files + # (for API endpoints that have file response). + # Default to use `Tempfile`. + # + # @return [String] + attr_accessor :temp_folder_path + + # Set this to false to skip verifying SSL certificate when calling API from https server. + # Default to true. + # + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + attr_accessor :verify_ssl + + # Set this to customize the certificate file to verify the peer. + # + # @return [String] the path to the certificate file + # + # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code: + # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 + attr_accessor :ssl_ca_cert + + attr_accessor :inject_format + + attr_accessor :force_ending_format + + class << self + def method_missing(method_name, *args, &block) + config = Configuration.instance + if config.respond_to?(method_name) + config.send(method_name, *args, &block) + else + super + end + end + end + + def initialize + @scheme = '{{scheme}}' + @host = '{{host}}' + @base_path = '{{contextPath}}' + @api_key = {} + @api_key_prefix = {} + @verify_ssl = true + @debugging = false + @inject_format = false + @force_ending_format = false + @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT) + end + + def api_client + @api_client ||= ApiClient.new + end + + def scheme=(scheme) + # remove :// from scheme + @scheme = scheme.sub(/:\/\//, '') + end + + def host=(host) + # remove http(s):// and anything after a slash + @host = host.sub(/https?:\/\//, '').split('/').first + end + + def base_path=(base_path) + # Add leading and trailing slashes to base_path + @base_path = "/#{base_path}".gsub(/\/+/, '/') + @base_path = "" if @base_path == "/" + end + + def base_url + url = "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}" + URI.encode(url) + end + + # Gets API key (with prefix if set). + # @param [String] param_name the parameter name of API key auth + def api_key_with_prefix(param_name) + if @api_key_prefix[param_name] + "#{@api_key_prefix[param_name]} #{@api_key[param_name]}" + else + @api_key[param_name] + end + end + + # Gets Basic Auth token string + def basic_auth_token + 'Basic ' + ["#{username}:#{password}"].pack('m').delete("\r\n") + end + + # Returns Auth Settings hash for api client. + def auth_settings + { +{{#authMethods}} +{{#isApiKey}} + '{{name}}' => + { + type: 'api_key', + in: {{#isKeyInHeader}}'header'{{/isKeyInHeader}}{{#isKeyInQuery}}'query'{{/isKeyInQuery}}, + key: '{{keyParamName}}', + value: api_key_with_prefix('{{keyParamName}}') + }, +{{/isApiKey}} +{{#isBasic}} + '{{name}}' => + { + type: 'basic', + in: 'header', + key: 'Authorization', + value: basic_auth_token + }, +{{/isBasic}} +{{/authMethods}} + } + end + end +end diff --git a/modules/swagger-codegen/src/main/resources/ruby/gem.mustache b/modules/swagger-codegen/src/main/resources/ruby/gem.mustache index 37203162d6b..eb0b8cfbf0f 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/gem.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/gem.mustache @@ -2,6 +2,7 @@ require '{{gemName}}/api_client' require '{{gemName}}/api_error' require '{{gemName}}/version' +require '{{gemName}}/configuration' # Models require '{{gemName}}/{{modelPackage}}/base_object' @@ -17,4 +18,19 @@ require '{{importPath}}' {{/apiInfo}} module {{moduleName}} + class << self + # Configure sdk using block. + # {{moduleName}}.configure do |config| + # config.username = "xxx" + # config.password = "xxx" + # end + # If no block given, return the configuration singleton instance. + def configure + if block_given? + yield Configuration.instance + else + Configuration.instance + end + end + end end diff --git a/samples/client/petstore/ruby/lib/petstore.rb b/samples/client/petstore/ruby/lib/petstore.rb index 9fa3a39f5f7..61640d687ac 100644 --- a/samples/client/petstore/ruby/lib/petstore.rb +++ b/samples/client/petstore/ruby/lib/petstore.rb @@ -2,6 +2,7 @@ require 'petstore/api_client' require 'petstore/api_error' require 'petstore/version' +require 'petstore/configuration' # Models require 'petstore/models/base_object' @@ -17,4 +18,19 @@ require 'petstore/api/pet_api' require 'petstore/api/store_api' module Petstore + class << self + # Configure sdk using block. + # Petstore.configure do |config| + # config.username = "xxx" + # config.password = "xxx" + # end + # If no block given, return the configuration singleton instance. + def configure + if block_given? + yield Configuration.instance + else + Configuration.instance + end + end + end end diff --git a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb index 5f21e703fb6..4b956aeadcc 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb @@ -5,18 +5,17 @@ module Petstore attr_accessor :api_client def initialize(api_client = nil) - @api_client = api_client || ApiClient.default + @api_client = api_client || Configuration.api_client end - # Update an existing pet # # @param [Hash] opts the optional parameters # @option opts [Pet] :body Pet object that needs to be added to the store # @return [nil] def update_pet(opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: PetApi#update_pet ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: PetApi#update_pet ..." end # resource path @@ -50,8 +49,8 @@ module Petstore :form_params => form_params, :body => post_body, :auth_names => auth_names) - if @api_client.debugging - @api_client.logger.debug "API called: PetApi#update_pet" + if Configuration.debugging + Configuration.logger.debug "API called: PetApi#update_pet" end return nil end @@ -62,8 +61,8 @@ module Petstore # @option opts [Pet] :body Pet object that needs to be added to the store # @return [nil] def add_pet(opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: PetApi#add_pet ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: PetApi#add_pet ..." end # resource path @@ -97,8 +96,8 @@ module Petstore :form_params => form_params, :body => post_body, :auth_names => auth_names) - if @api_client.debugging - @api_client.logger.debug "API called: PetApi#add_pet" + if Configuration.debugging + Configuration.logger.debug "API called: PetApi#add_pet" end return nil end @@ -109,8 +108,8 @@ module Petstore # @option opts [Array] :status Status values that need to be considered for filter # @return [Array] def find_pets_by_status(opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: PetApi#find_pets_by_status ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: PetApi#find_pets_by_status ..." end # resource path @@ -146,8 +145,8 @@ module Petstore :body => post_body, :auth_names => auth_names, :return_type => 'Array') - if @api_client.debugging - @api_client.logger.debug "API called: PetApi#find_pets_by_status. Result: #{result.inspect}" + if Configuration.debugging + Configuration.logger.debug "API called: PetApi#find_pets_by_status. Result: #{result.inspect}" end return result end @@ -158,8 +157,8 @@ module Petstore # @option opts [Array] :tags Tags to filter by # @return [Array] def find_pets_by_tags(opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: PetApi#find_pets_by_tags ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: PetApi#find_pets_by_tags ..." end # resource path @@ -195,8 +194,8 @@ module Petstore :body => post_body, :auth_names => auth_names, :return_type => 'Array') - if @api_client.debugging - @api_client.logger.debug "API called: PetApi#find_pets_by_tags. Result: #{result.inspect}" + if Configuration.debugging + Configuration.logger.debug "API called: PetApi#find_pets_by_tags. Result: #{result.inspect}" end return result end @@ -207,8 +206,8 @@ module Petstore # @param [Hash] opts the optional parameters # @return [Pet] def get_pet_by_id(pet_id, opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: PetApi#get_pet_by_id ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: PetApi#get_pet_by_id ..." end # verify the required parameter 'pet_id' is set @@ -246,8 +245,8 @@ module Petstore :body => post_body, :auth_names => auth_names, :return_type => 'Pet') - if @api_client.debugging - @api_client.logger.debug "API called: PetApi#get_pet_by_id. Result: #{result.inspect}" + if Configuration.debugging + Configuration.logger.debug "API called: PetApi#get_pet_by_id. Result: #{result.inspect}" end return result end @@ -260,8 +259,8 @@ module Petstore # @option opts [String] :status Updated status of the pet # @return [nil] def update_pet_with_form(pet_id, opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: PetApi#update_pet_with_form ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: PetApi#update_pet_with_form ..." end # verify the required parameter 'pet_id' is set @@ -300,8 +299,8 @@ module Petstore :form_params => form_params, :body => post_body, :auth_names => auth_names) - if @api_client.debugging - @api_client.logger.debug "API called: PetApi#update_pet_with_form" + if Configuration.debugging + Configuration.logger.debug "API called: PetApi#update_pet_with_form" end return nil end @@ -313,8 +312,8 @@ module Petstore # @option opts [String] :api_key # @return [nil] def delete_pet(pet_id, opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: PetApi#delete_pet ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: PetApi#delete_pet ..." end # verify the required parameter 'pet_id' is set @@ -352,8 +351,8 @@ module Petstore :form_params => form_params, :body => post_body, :auth_names => auth_names) - if @api_client.debugging - @api_client.logger.debug "API called: PetApi#delete_pet" + if Configuration.debugging + Configuration.logger.debug "API called: PetApi#delete_pet" end return nil end @@ -366,8 +365,8 @@ module Petstore # @option opts [File] :file file to upload # @return [nil] def upload_file(pet_id, opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: PetApi#upload_file ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: PetApi#upload_file ..." end # verify the required parameter 'pet_id' is set @@ -406,10 +405,14 @@ module Petstore :form_params => form_params, :body => post_body, :auth_names => auth_names) - if @api_client.debugging - @api_client.logger.debug "API called: PetApi#upload_file" + if Configuration.debugging + Configuration.logger.debug "API called: PetApi#upload_file" end return nil end end end + + + + diff --git a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb index ec9f16001f2..235ff1c4106 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb @@ -5,17 +5,16 @@ module Petstore attr_accessor :api_client def initialize(api_client = nil) - @api_client = api_client || ApiClient.default + @api_client = api_client || Configuration.api_client end - # Returns pet inventories by status # Returns a map of status codes to quantities # @param [Hash] opts the optional parameters # @return [Hash] def get_inventory(opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: StoreApi#get_inventory ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: StoreApi#get_inventory ..." end # resource path @@ -50,8 +49,8 @@ module Petstore :body => post_body, :auth_names => auth_names, :return_type => 'Hash') - if @api_client.debugging - @api_client.logger.debug "API called: StoreApi#get_inventory. Result: #{result.inspect}" + if Configuration.debugging + Configuration.logger.debug "API called: StoreApi#get_inventory. Result: #{result.inspect}" end return result end @@ -62,8 +61,8 @@ module Petstore # @option opts [Order] :body order placed for purchasing the pet # @return [Order] def place_order(opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: StoreApi#place_order ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: StoreApi#place_order ..." end # resource path @@ -98,8 +97,8 @@ module Petstore :body => post_body, :auth_names => auth_names, :return_type => 'Order') - if @api_client.debugging - @api_client.logger.debug "API called: StoreApi#place_order. Result: #{result.inspect}" + if Configuration.debugging + Configuration.logger.debug "API called: StoreApi#place_order. Result: #{result.inspect}" end return result end @@ -110,8 +109,8 @@ module Petstore # @param [Hash] opts the optional parameters # @return [Order] def get_order_by_id(order_id, opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: StoreApi#get_order_by_id ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: StoreApi#get_order_by_id ..." end # verify the required parameter 'order_id' is set @@ -149,8 +148,8 @@ module Petstore :body => post_body, :auth_names => auth_names, :return_type => 'Order') - if @api_client.debugging - @api_client.logger.debug "API called: StoreApi#get_order_by_id. Result: #{result.inspect}" + if Configuration.debugging + Configuration.logger.debug "API called: StoreApi#get_order_by_id. Result: #{result.inspect}" end return result end @@ -161,8 +160,8 @@ module Petstore # @param [Hash] opts the optional parameters # @return [nil] def delete_order(order_id, opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: StoreApi#delete_order ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: StoreApi#delete_order ..." end # verify the required parameter 'order_id' is set @@ -199,10 +198,14 @@ module Petstore :form_params => form_params, :body => post_body, :auth_names => auth_names) - if @api_client.debugging - @api_client.logger.debug "API called: StoreApi#delete_order" + if Configuration.debugging + Configuration.logger.debug "API called: StoreApi#delete_order" end return nil end end end + + + + diff --git a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb index eda69c97282..f4672e2a358 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb @@ -5,18 +5,17 @@ module Petstore attr_accessor :api_client def initialize(api_client = nil) - @api_client = api_client || ApiClient.default + @api_client = api_client || Configuration.api_client end - # Create user # This can only be done by the logged in user. # @param [Hash] opts the optional parameters # @option opts [User] :body Created user object # @return [nil] def create_user(opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: UserApi#create_user ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: UserApi#create_user ..." end # resource path @@ -50,8 +49,8 @@ module Petstore :form_params => form_params, :body => post_body, :auth_names => auth_names) - if @api_client.debugging - @api_client.logger.debug "API called: UserApi#create_user" + if Configuration.debugging + Configuration.logger.debug "API called: UserApi#create_user" end return nil end @@ -62,8 +61,8 @@ module Petstore # @option opts [Array] :body List of user object # @return [nil] def create_users_with_array_input(opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: UserApi#create_users_with_array_input ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: UserApi#create_users_with_array_input ..." end # resource path @@ -97,8 +96,8 @@ module Petstore :form_params => form_params, :body => post_body, :auth_names => auth_names) - if @api_client.debugging - @api_client.logger.debug "API called: UserApi#create_users_with_array_input" + if Configuration.debugging + Configuration.logger.debug "API called: UserApi#create_users_with_array_input" end return nil end @@ -109,8 +108,8 @@ module Petstore # @option opts [Array] :body List of user object # @return [nil] def create_users_with_list_input(opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: UserApi#create_users_with_list_input ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: UserApi#create_users_with_list_input ..." end # resource path @@ -144,8 +143,8 @@ module Petstore :form_params => form_params, :body => post_body, :auth_names => auth_names) - if @api_client.debugging - @api_client.logger.debug "API called: UserApi#create_users_with_list_input" + if Configuration.debugging + Configuration.logger.debug "API called: UserApi#create_users_with_list_input" end return nil end @@ -157,8 +156,8 @@ module Petstore # @option opts [String] :password The password for login in clear text # @return [String] def login_user(opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: UserApi#login_user ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: UserApi#login_user ..." end # resource path @@ -195,8 +194,8 @@ module Petstore :body => post_body, :auth_names => auth_names, :return_type => 'String') - if @api_client.debugging - @api_client.logger.debug "API called: UserApi#login_user. Result: #{result.inspect}" + if Configuration.debugging + Configuration.logger.debug "API called: UserApi#login_user. Result: #{result.inspect}" end return result end @@ -206,8 +205,8 @@ module Petstore # @param [Hash] opts the optional parameters # @return [nil] def logout_user(opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: UserApi#logout_user ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: UserApi#logout_user ..." end # resource path @@ -241,8 +240,8 @@ module Petstore :form_params => form_params, :body => post_body, :auth_names => auth_names) - if @api_client.debugging - @api_client.logger.debug "API called: UserApi#logout_user" + if Configuration.debugging + Configuration.logger.debug "API called: UserApi#logout_user" end return nil end @@ -253,8 +252,8 @@ module Petstore # @param [Hash] opts the optional parameters # @return [User] def get_user_by_name(username, opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: UserApi#get_user_by_name ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: UserApi#get_user_by_name ..." end # verify the required parameter 'username' is set @@ -292,8 +291,8 @@ module Petstore :body => post_body, :auth_names => auth_names, :return_type => 'User') - if @api_client.debugging - @api_client.logger.debug "API called: UserApi#get_user_by_name. Result: #{result.inspect}" + if Configuration.debugging + Configuration.logger.debug "API called: UserApi#get_user_by_name. Result: #{result.inspect}" end return result end @@ -305,8 +304,8 @@ module Petstore # @option opts [User] :body Updated user object # @return [nil] def update_user(username, opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: UserApi#update_user ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: UserApi#update_user ..." end # verify the required parameter 'username' is set @@ -343,8 +342,8 @@ module Petstore :form_params => form_params, :body => post_body, :auth_names => auth_names) - if @api_client.debugging - @api_client.logger.debug "API called: UserApi#update_user" + if Configuration.debugging + Configuration.logger.debug "API called: UserApi#update_user" end return nil end @@ -355,8 +354,8 @@ module Petstore # @param [Hash] opts the optional parameters # @return [nil] def delete_user(username, opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: UserApi#delete_user ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: UserApi#delete_user ..." end # verify the required parameter 'username' is set @@ -393,10 +392,14 @@ module Petstore :form_params => form_params, :body => post_body, :auth_names => auth_names) - if @api_client.debugging - @api_client.logger.debug "API called: UserApi#delete_user" + if Configuration.debugging + Configuration.logger.debug "API called: UserApi#delete_user" end return nil end end end + + + + diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index 6d4dda8f939..33b53238b02 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -7,69 +7,8 @@ require 'uri' module Petstore class ApiClient - attr_accessor :scheme, :host, :base_path, :user_agent - # Defines the username used with HTTP basic authentication. - # - # @return [String] - attr_accessor :username - - # Defines the password used with HTTP basic authentication. - # - # @return [String] - attr_accessor :password - - # Defines API keys used with API Key authentications. - # - # @return [Hash] key: parameter name, value: parameter value (API key) - # - # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string) - # config.api_key['api_key'] = 'xxx' - attr_accessor :api_key - - # Defines API key prefixes used with API Key authentications. - # - # @return [Hash] key: parameter name, value: API key prefix - # - # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers) - # config.api_key_prefix['api_key'] = 'Token' - attr_accessor :api_key_prefix - - # Set this to false to skip verifying SSL certificate when calling API from https server. - # Default to true. - # - # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. - # - # @return [true, false] - attr_accessor :verify_ssl - - # Set this to customize the certificate file to verify the peer. - # - # @return [String] the path to the certificate file - # - # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code: - # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 - attr_accessor :ssl_ca_cert - - # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response - # details will be logged with `logger.debug` (see the `logger` attribute). - # Default to false. - # - # @return [true, false] - attr_accessor :debugging - - # Defines the logger used for debugging. - # Default to `Rails.logger` (when in Rails) or logging to STDOUT. - # - # @return [#debug] - attr_accessor :logger - - # Defines the temporary folder to store downloaded files - # (for API endpoints that have file response). - # Default to use `Tempfile`. - # - # @return [String] - attr_accessor :temp_folder_path + attr_accessor :host # Defines the headers to be used in HTTP requests of all API calls by default. # @@ -79,59 +18,14 @@ module Petstore # Stores the HTTP response from the last API call using this API client. attr_accessor :last_response - # The constructor accepts a optional block to configure the API client. - # - # @example - # Petstore::ApiClient.new do |client| - # client.api_key['api_key'] = 'your key' # api key authentication - # client.username = 'your username' # username for http basic authentication - # client.password = 'your password' # password for http basic authentication - # end - def initialize(&block) + def initialize(host = nil) + @host = host || Configuration.base_url @format = 'json' - @scheme = 'http' - @host = 'petstore.swagger.io' - @base_path = '/v2' @user_agent = "ruby-swagger-#{VERSION}" - @inject_format = false - @force_ending_format = false - @default_headers = { 'Content-Type' => "application/#{@format.downcase}", 'User-Agent' => @user_agent } - - # keys for API key authentication (param-name => api-key) - @api_key = {} - @api_key_prefix = {} - - @verify_ssl = true - - @debugging = false - @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT) - - configure(&block) - end - - # Default API client. - def self.default - @@default ||= ApiClient.new - end - - # Call this method to modify defaults in your initializers. - def configure - yield(self) if block_given? - - # remove :// from scheme - @scheme.sub!(/:\/\//, '') - - # remove http(s):// and anything after a slash - @host.sub!(/https?:\/\//, '') - @host = @host.split('/').first - - # Add leading and trailing slashes to base_path - @base_path = "/#{@base_path}".gsub(/\/+/, '/') - @base_path = "" if @base_path == "/" end def call_api(http_method, path, opts = {}) @@ -141,8 +35,8 @@ module Petstore # record as last response @last_response = response - if debugging - logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" + if Configuration.debugging + Configuration.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" end unless response.success? @@ -153,9 +47,9 @@ module Petstore end if opts[:return_type] - return deserialize(response, opts[:return_type]) + deserialize(response, opts[:return_type]) else - return nil + nil end end @@ -183,8 +77,8 @@ module Petstore if [:post, :patch, :put, :delete].include?(http_method) req_body = build_request_body(header_params, form_params, opts[:body]) req_opts.update :body => req_body - if debugging - logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n" + if Configuration.debugging + Configuration.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n" end end @@ -279,13 +173,13 @@ module Petstore File.open(path, 'w') { |file| file.write(response.body) } logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards" - return File.new(path) + File.new(path) end def build_request_url(path) - url = [host, base_path, path].join('/').gsub(/\/+/, '/') - url = "#{scheme}://#{url}" - URI.encode(url) + # Add leading and trailing slashes to path + path = "/#{path}".gsub(/\/+/, '/') + URI.encode(host + path) end def build_request_body(header_params, form_params, body) @@ -300,36 +194,22 @@ module Petstore else data = nil end - return data + data end - # Update hearder and query params based on authentication settings. def update_params_for_auth!(header_params, query_params, auth_names) - return unless auth_names - auth_names.each do |auth_name| - case auth_name - when 'api_key' - header_params ||= {} - header_params['api_key'] = get_api_key_with_prefix('api_key') - when 'petstore_auth' - # TODO: support oauth - + Array(auth_names).each do |auth_name| + auth_setting = Configuration.auth_settings[auth_name] + next unless auth_setting + case auth_setting[:in] + when 'header' then header_params[auth_setting[:key]] = auth_setting[:value] + when 'query' then query_params[auth_setting[:key]] = auth_settings[:value] + else fail ArgumentError, 'Authentication token must be in `query` of `header`' end end end - # Get API key (with prefix if set). - # @param [String] param_name the parameter name of API key auth - def get_api_key_with_prefix(param_name) - if @api_key_prefix[param_name] - "#{@api_key_prefix[param_name]} #{@api_key[param_name]}" - else - @api_key[param_name] - end - end - - def user_agent=(user_agent) @user_agent = user_agent @default_headers['User-Agent'] = @user_agent diff --git a/samples/client/petstore/ruby/lib/petstore/configuration.rb b/samples/client/petstore/ruby/lib/petstore/configuration.rb new file mode 100644 index 00000000000..83df41b5e05 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/configuration.rb @@ -0,0 +1,164 @@ +require 'uri' +require 'singleton' + +module Petstore + class Configuration + + include Singleton + + # Default api client + attr_accessor :api_client + + # Defines url scheme + attr_accessor :scheme + + # Defines url host + attr_accessor :host + + # Defines url base path + attr_accessor :base_path + + # Defines API keys used with API Key authentications. + # + # @return [Hash] key: parameter name, value: parameter value (API key) + # + # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string) + # config.api_key['api_key'] = 'xxx' + attr_accessor :api_key + + # Defines API key prefixes used with API Key authentications. + # + # @return [Hash] key: parameter name, value: API key prefix + # + # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers) + # config.api_key_prefix['api_key'] = 'Token' + attr_accessor :api_key_prefix + + # Defines the username used with HTTP basic authentication. + # + # @return [String] + attr_accessor :username + + # Defines the password used with HTTP basic authentication. + # + # @return [String] + attr_accessor :password + + # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response + # details will be logged with `logger.debug` (see the `logger` attribute). + # Default to false. + # + # @return [true, false] + attr_accessor :debugging + + # Defines the logger used for debugging. + # Default to `Rails.logger` (when in Rails) or logging to STDOUT. + # + # @return [#debug] + attr_accessor :logger + + # Defines the temporary folder to store downloaded files + # (for API endpoints that have file response). + # Default to use `Tempfile`. + # + # @return [String] + attr_accessor :temp_folder_path + + # Set this to false to skip verifying SSL certificate when calling API from https server. + # Default to true. + # + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + attr_accessor :verify_ssl + + # Set this to customize the certificate file to verify the peer. + # + # @return [String] the path to the certificate file + # + # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code: + # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 + attr_accessor :ssl_ca_cert + + attr_accessor :inject_format + + attr_accessor :force_ending_format + + class << self + def method_missing(method_name, *args, &block) + config = Configuration.instance + if config.respond_to?(method_name) + config.send(method_name, *args, &block) + else + super + end + end + end + + def initialize + @scheme = 'http' + @host = 'petstore.swagger.io' + @base_path = '/v2' + @api_key = {} + @api_key_prefix = {} + @verify_ssl = true + @debugging = false + @inject_format = false + @force_ending_format = false + @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT) + end + + def api_client + @api_client ||= ApiClient.new + end + + def scheme=(scheme) + # remove :// from scheme + @scheme = scheme.sub(/:\/\//, '') + end + + def host=(host) + # remove http(s):// and anything after a slash + @host = host.sub(/https?:\/\//, '').split('/').first + end + + def base_path=(base_path) + # Add leading and trailing slashes to base_path + @base_path = "/#{base_path}".gsub(/\/+/, '/') + @base_path = "" if @base_path == "/" + end + + def base_url + url = "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}" + URI.encode(url) + end + + # Gets API key (with prefix if set). + # @param [String] param_name the parameter name of API key auth + def api_key_with_prefix(param_name) + if @api_key_prefix[param_name] + "#{@api_key_prefix[param_name]} #{@api_key[param_name]}" + else + @api_key[param_name] + end + end + + # Gets Basic Auth token string + def basic_auth_token + 'Basic ' + ["#{username}:#{password}"].pack('m').delete("\r\n") + end + + # Returns Auth Settings hash for api client. + def auth_settings + { + 'api_key' => + { + type: 'api_key', + in: 'header', + key: 'api_key', + value: api_key_with_prefix('api_key') + }, + } + end + end +end diff --git a/samples/client/petstore/ruby/spec/api_client_spec.rb b/samples/client/petstore/ruby/spec/api_client_spec.rb index 69c4490c960..b63ec94ccaa 100644 --- a/samples/client/petstore/ruby/spec/api_client_spec.rb +++ b/samples/client/petstore/ruby/spec/api_client_spec.rb @@ -9,40 +9,35 @@ describe Petstore::ApiClient do context 'host' do it 'removes http from host' do - c = Petstore::ApiClient.new - c.configure {|c| c.host = 'http://example.com' } - c.host.should == 'example.com' + Petstore.configure { |c| c.host = 'http://example.com' } + Petstore.configure.host.should == 'example.com' end it 'removes https from host' do - c = Petstore::ApiClient.new {|c| c.host = 'https://wookiee.com' } - c.host.should == 'wookiee.com' + Petstore.configure { |c| c.host = 'https://wookiee.com' } + Petstore.configure.host.should == 'wookiee.com' end it 'removes trailing path from host' do - c = Petstore::ApiClient.new - c.configure {|c| c.host = 'hobo.com/v4' } - c.host.should == 'hobo.com' + Petstore.configure { |c| c.host = 'hobo.com/v4' } + Petstore.configure.host.should == 'hobo.com' end end context 'base_path' do it "prepends a slash to base_path" do - c = Petstore::ApiClient.new - c.configure {|c| c.base_path = 'v4/dog' } - c.base_path.should == '/v4/dog' + Petstore.configure { |c| c.base_path = 'v4/dog' } + Petstore.configure.base_path.should == '/v4/dog' end it "doesn't prepend a slash if one is already there" do - c = Petstore::ApiClient.new - c.configure {|c| c.base_path = '/v4/dog' } - c.base_path.should == '/v4/dog' + Petstore.configure { |c| c.base_path = '/v4/dog' } + Petstore.configure.base_path.should == '/v4/dog' end it "ends up as a blank string if nil" do - c = Petstore::ApiClient.new - c.configure {|c| c.base_path = nil } - c.base_path.should == '' + Petstore.configure { |c| c.base_path = nil } + Petstore.configure.base_path.should == '' end end @@ -52,10 +47,13 @@ describe Petstore::ApiClient do describe "#update_params_for_auth!" do it "sets header api-key parameter with prefix" do - api_client = Petstore::ApiClient.new do |c| + Petstore.configure do |c| c.api_key_prefix['api_key'] = 'PREFIX' c.api_key['api_key'] = 'special-key' end + + api_client = Petstore::ApiClient.new + header_params = {} query_params = {} auth_names = ['api_key', 'unknown'] @@ -65,10 +63,13 @@ describe Petstore::ApiClient do end it "sets header api-key parameter without prefix" do - api_client = Petstore::ApiClient.new do |c| + Petstore.configure do |c| c.api_key_prefix['api_key'] = nil c.api_key['api_key'] = 'special-key' end + + api_client = Petstore::ApiClient.new + header_params = {} query_params = {} auth_names = ['api_key', 'unknown'] From 31d948fc16594b66e21ad27ca23b041067d6f780 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Tue, 18 Aug 2015 14:35:54 +0800 Subject: [PATCH 10/17] Update readme of ruby client --- samples/client/petstore/ruby/README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index ad85f74315b..dd6258ec696 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -42,12 +42,12 @@ ruby -Ilib script.rb ```ruby require 'petstore' -Petstore::ApiClient.default.configure do |client| - client.api_key['api_key'] = 'special-key' - client.host = 'petstore.swagger.io' - client.base_path = '/v2' +Petstore.configure do |config| + config.api_key['api_key'] = 'special-key' + config.host = 'petstore.swagger.io' + config.base_path = '/v2' # enable debugging (default is disabled) - client.debugging = true + config.debugging = true end pet_api = Petstore::PetApi.new From 828f8694c86ae12702d976d064f305c8a84e4d99 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Tue, 18 Aug 2015 16:13:32 +0800 Subject: [PATCH 11/17] Fix typo in ruby client --- .../swagger-codegen/src/main/resources/ruby/api_client.mustache | 2 +- samples/client/petstore/ruby/lib/petstore/api_client.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache index 6bc6df0430b..31c5035f559 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache @@ -204,7 +204,7 @@ module {{moduleName}} next unless auth_setting case auth_setting[:in] when 'header' then header_params[auth_setting[:key]] = auth_setting[:value] - when 'query' then query_params[auth_setting[:key]] = auth_settings[:value] + when 'query' then query_params[auth_setting[:key]] = auth_setting[:value] else fail ArgumentError, 'Authentication token must be in `query` of `header`' end end diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index 33b53238b02..68fa5f9d9f1 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -204,7 +204,7 @@ module Petstore next unless auth_setting case auth_setting[:in] when 'header' then header_params[auth_setting[:key]] = auth_setting[:value] - when 'query' then query_params[auth_setting[:key]] = auth_settings[:value] + when 'query' then query_params[auth_setting[:key]] = auth_setting[:value] else fail ArgumentError, 'Authentication token must be in `query` of `header`' end end From 7be6e971fac73efabb95c81fc1bac05e660a9e37 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Tue, 18 Aug 2015 20:21:56 +0800 Subject: [PATCH 12/17] Update api client of ruby client. Update ApiClient#build_request, change `@verify_ssl`, `@ssl_ca_cert`, `@debugging` to `Configuration.verify_ssl`, `Configuration.ssl_ca_cert`, `Configuration.debugging`. --- .../src/main/resources/ruby/api_client.mustache | 6 +++--- samples/client/petstore/ruby/lib/petstore/api_client.rb | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache index 31c5035f559..ea98307aead 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache @@ -69,9 +69,9 @@ module {{moduleName}} :method => http_method, :headers => header_params, :params => query_params, - :ssl_verifypeer => @verify_ssl, - :cainfo => @ssl_ca_cert, - :verbose => @debugging + :ssl_verifypeer => Configuration.verify_ssl, + :cainfo => Configuration.ssl_ca_cert, + :verbose => Configuration.debugging } if [:post, :patch, :put, :delete].include?(http_method) diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index 68fa5f9d9f1..4cb8934efe4 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -69,9 +69,9 @@ module Petstore :method => http_method, :headers => header_params, :params => query_params, - :ssl_verifypeer => @verify_ssl, - :cainfo => @ssl_ca_cert, - :verbose => @debugging + :ssl_verifypeer => Configuration.verify_ssl, + :cainfo => Configuration.ssl_ca_cert, + :verbose => Configuration.debugging } if [:post, :patch, :put, :delete].include?(http_method) From 030e45982cd61cba0cdabd619b8cd30c109fd019 Mon Sep 17 00:00:00 2001 From: xhh Date: Thu, 20 Aug 2015 10:45:40 +0800 Subject: [PATCH 13/17] Add back support of file uploading to Ruby client --- .../src/main/resources/ruby/swagger/request.mustache | 3 ++- samples/client/petstore/ruby/lib/petstore/swagger/request.rb | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache index dd39449e1f3..98e0a62fcd5 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache @@ -95,7 +95,8 @@ module {{moduleName}} # For form parameters, remove empty value def outgoing_body # http form - if headers['Content-Type'] == 'application/x-www-form-urlencoded' + if headers['Content-Type'] == 'application/x-www-form-urlencoded' || + headers['Content-Type'] == 'multipart/form-data' data = form_params.dup data.each do |key, value| data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter diff --git a/samples/client/petstore/ruby/lib/petstore/swagger/request.rb b/samples/client/petstore/ruby/lib/petstore/swagger/request.rb index ecb8cff5643..8bb05af7078 100644 --- a/samples/client/petstore/ruby/lib/petstore/swagger/request.rb +++ b/samples/client/petstore/ruby/lib/petstore/swagger/request.rb @@ -94,7 +94,8 @@ module Petstore # For form parameters, remove empty value def outgoing_body # http form - if headers['Content-Type'] == 'application/x-www-form-urlencoded' + if headers['Content-Type'] == 'application/x-www-form-urlencoded' || + headers['Content-Type'] == 'multipart/form-data' data = form_params.dup data.each do |key, value| data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter From 0d399d3f6a37340065d245cfc1e12a44a003112b Mon Sep 17 00:00:00 2001 From: xhh Date: Thu, 20 Aug 2015 11:07:20 +0800 Subject: [PATCH 14/17] Add spec for file uploading --- samples/client/petstore/ruby/spec/pet_spec.rb | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/samples/client/petstore/ruby/spec/pet_spec.rb b/samples/client/petstore/ruby/spec/pet_spec.rb index 8c33c3a9cde..6aa148f91a2 100644 --- a/samples/client/petstore/ruby/spec/pet_spec.rb +++ b/samples/client/petstore/ruby/spec/pet_spec.rb @@ -105,5 +105,16 @@ describe "Pet" do pet.id.should == 10002 pet.name.should == "RUBY UNIT TESTING" end + + it "should upload a file to a pet" do + pet = Petstore::Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING") + result = Petstore::PetApi.add_pet(:body => pet) + # nothing is returned + result.should be_nil + + result = Petstore::PetApi.upload_file(10002, file: File.new('hello.txt')) + # nothing is returned + result.should be_nil + end end end From 2e3f94c2a5c4f07e11e0b7f0d502b999ce2b2a53 Mon Sep 17 00:00:00 2001 From: xhh Date: Thu, 20 Aug 2015 11:18:05 +0800 Subject: [PATCH 15/17] Add file used in test: hello.txt --- samples/client/petstore/ruby/hello.txt | 1 + 1 file changed, 1 insertion(+) create mode 100644 samples/client/petstore/ruby/hello.txt diff --git a/samples/client/petstore/ruby/hello.txt b/samples/client/petstore/ruby/hello.txt new file mode 100644 index 00000000000..6769dd60bdf --- /dev/null +++ b/samples/client/petstore/ruby/hello.txt @@ -0,0 +1 @@ +Hello world! \ No newline at end of file From 4477009ef80df7f8a10c29b16a358c99b3d66aae Mon Sep 17 00:00:00 2001 From: geekerzp Date: Sat, 29 Aug 2015 16:19:43 +0800 Subject: [PATCH 16/17] Handle special characters in parameter names in ruby client --- .../io/swagger/codegen/languages/RubyClientCodegen.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java index 6c6d073e9c9..59b62b0be6a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java @@ -196,8 +196,10 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toVarName(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); + // remove trailing special characters, e.g. "post[created-at]!!" => "post[created-at" + name = name.replaceAll("\\W+\\z", ""); + // replace special characters with _, e.g. "post[created-at" => "post_created_at" + name = name.replaceAll("\\W+", "_"); // if it's all uppper case, convert to lower case if (name.matches("^[A-Z_]*$")) { From 7c60e2097f887f9d7cbb95b015b3b1c4d301eeb3 Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 2 Sep 2015 12:00:27 +0800 Subject: [PATCH 17/17] Update API client initialization in Ruby test --- samples/client/petstore/ruby/spec/spec_helper.rb | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/samples/client/petstore/ruby/spec/spec_helper.rb b/samples/client/petstore/ruby/spec/spec_helper.rb index f8e5992a342..b8ba0f73975 100644 --- a/samples/client/petstore/ruby/spec/spec_helper.rb +++ b/samples/client/petstore/ruby/spec/spec_helper.rb @@ -36,11 +36,7 @@ end # help #end -API_CLIENT = Petstore::ApiClient.new do |config| - config.api_key['api_key'] = 'special-key' - config.host = 'petstore.swagger.io' - config.base_path = '/v2' -end +API_CLIENT = Petstore::ApiClient.new # always delete and then re-create the pet object with 10002 def prepare_pet(pet_api)