From 104bcc1f89a5b086e820fd9fec9f267136eefb6e Mon Sep 17 00:00:00 2001 From: xhh Date: Sun, 19 Apr 2015 00:35:58 +0800 Subject: [PATCH] Organize generated Ruby code into a module --- .../wordnik/swagger/codegen/CodegenModel.java | 4 +- .../swagger/codegen/DefaultCodegen.java | 1 + .../swagger/codegen/DefaultGenerator.java | 1 + .../codegen/languages/RubyClientCodegen.java | 75 +-- .../src/main/resources/ruby/api.mustache | 84 ++-- .../src/main/resources/ruby/model.mustache | 71 +-- .../ruby/swagger-client.gemspec.mustache | 8 +- .../resources/ruby/swagger-client.mustache | 29 +- .../src/main/resources/ruby/swagger.mustache | 134 +++-- .../ruby/swagger/configuration.mustache | 33 +- .../resources/ruby/swagger/request.mustache | 466 +++++++++--------- .../resources/ruby/swagger/response.mustache | 124 ++--- .../resources/ruby/swagger/version.mustache | 7 +- 13 files changed, 531 insertions(+), 506 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java index 169886da22e..274b77b4e9d 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java @@ -7,10 +7,10 @@ import java.util.*; public class CodegenModel { public String parent; - public String name, classname, description, classVarName, modelJson; + public String name, classname, importPath, description, classVarName, modelJson; public String defaultValue; public List vars = new ArrayList(); public Set imports = new HashSet(); public Boolean hasVars, emptyVars, hasMoreModels; public ExternalDocs externalDocs; -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index 6f51374c536..3642e8de1b6 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -428,6 +428,7 @@ public class DefaultCodegen { m.name = name; m.description = escapeText(model.getDescription()); m.classname = toModelName(name); + m.importPath = toModelImport(name); m.classVarName = toVarName(name); m.modelJson = Json.pretty(model); m.externalDocs = model.getExternalDocs(); diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java index 17509973215..395f298eb07 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -165,6 +165,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { operation.putAll(config.additionalProperties()); operation.put("classname", config.toApiName(tag)); operation.put("classVarName", config.toApiVarName(tag)); + operation.put("importPath", config.toApiImport(tag)); allOperations.add(new HashMap(operation)); for (int i = 0; i < allOperations.size(); i++) { diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RubyClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RubyClientCodegen.java index 99f56bf5d41..5fb8ee5eb8f 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RubyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RubyClientCodegen.java @@ -8,10 +8,9 @@ import java.util.*; import java.io.File; public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "com.wordnik.client"; - protected String groupId = "com.wordnik"; - protected String artifactId = "swagger-client"; - protected String artifactVersion = "1.0.0"; + protected String gemName = "swagger-client"; + protected String moduleName = null; + protected String libFolder = "lib"; public CodegenType getTag() { return CodegenType.CLIENT; @@ -25,10 +24,18 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { return "Generates a Ruby client library."; } + /** + * Generate Ruby module name from the gem name, e.g. use "SwaggerClient" for "swagger-client". + */ + public String generateModuleName() { + return camelize(gemName.replaceAll("[^\\w]+", "_")); + } + public RubyClientCodegen() { super(); - modelPackage = "models"; - apiPackage = "lib"; + moduleName = generateModuleName(); + modelPackage = gemName + "/models"; + apiPackage = gemName + "/api"; outputFolder = "generated-code/ruby"; modelTemplateFiles.put("model.mustache", ".rb"); apiTemplateFiles.put("api.mustache", ".rb"); @@ -39,17 +46,15 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { reservedWords = new HashSet ( Arrays.asList( - "__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__", + "__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__", "begin", "defined?", "ensure", "module", "redo", "super", "until", "BEGIN", - "break", "do", "false", "next", "rescue", "then", "when", "END", "case", + "break", "do", "false", "next", "rescue", "then", "when", "END", "case", "else", "for", "nil", "retry", "true", "while", "alias", "class", "elsif", "if", "not", "return", "undef", "yield") ); - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put("gemName", gemName); + additionalProperties.put("moduleName", moduleName); languageSpecificPrimitives.add("int"); languageSpecificPrimitives.add("array"); @@ -64,15 +69,18 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("List", "array"); typeMapping.put("map", "map"); - supportingFiles.add(new SupportingFile("swagger-client.gemspec.mustache", "", "swagger-client.gemspec")); - supportingFiles.add(new SupportingFile("swagger-client.mustache", "", "lib/swagger-client.rb")); - supportingFiles.add(new SupportingFile("swagger.mustache", "", "lib/swagger.rb")); - supportingFiles.add(new SupportingFile("monkey.mustache", "", "lib/monkey.rb")); - supportingFiles.add(new SupportingFile("swagger/request.mustache", "", "lib/swagger/request.rb")); - supportingFiles.add(new SupportingFile("swagger/response.mustache", "", "lib/swagger/response.rb")); - supportingFiles.add(new SupportingFile("swagger/version.mustache", "", "lib/swagger/version.rb")); - supportingFiles.add(new SupportingFile("swagger/configuration.mustache", "", "lib/swagger/configuration.rb")); - supportingFiles.add(new SupportingFile("base_object.mustache", "", "models/base_object.rb")); + String baseFolder = "lib/" + gemName; + String swaggerFolder = baseFolder + "/swagger"; + String modelFolder = baseFolder + "/models"; + supportingFiles.add(new SupportingFile("swagger-client.gemspec.mustache", "", gemName + ".gemspec")); + supportingFiles.add(new SupportingFile("swagger-client.mustache", "lib", gemName + ".rb")); + supportingFiles.add(new SupportingFile("monkey.mustache", baseFolder, "monkey.rb")); + supportingFiles.add(new SupportingFile("swagger.mustache", baseFolder, "swagger.rb")); + supportingFiles.add(new SupportingFile("swagger/request.mustache", swaggerFolder, "request.rb")); + supportingFiles.add(new SupportingFile("swagger/response.mustache", swaggerFolder, "response.rb")); + supportingFiles.add(new SupportingFile("swagger/version.mustache", swaggerFolder, "version.rb")); + supportingFiles.add(new SupportingFile("swagger/configuration.mustache", swaggerFolder, "configuration.rb")); + supportingFiles.add(new SupportingFile("base_object.mustache", modelFolder, "base_object.rb")); } @Override @@ -82,11 +90,11 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String apiFileFolder() { - return outputFolder + "/" + apiPackage().replace('.', File.separatorChar); + return outputFolder + File.separatorChar + "lib" + File.separatorChar + gemName + File.separatorChar + "api"; } public String modelFileFolder() { - return outputFolder + "/" + modelPackage().replace('.', File.separatorChar); + return outputFolder + File.separatorChar + "lib" + File.separatorChar + gemName + File.separatorChar + "models"; } @Override @@ -150,13 +158,13 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { // should be the same as variable name return toVarName(name); } - + @Override public String toModelName(String name) { // model name cannot use reserved keyword, e.g. return if(reservedWords.contains(name)) throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); - + // camelize the model name // phone_number => PhoneNumber return camelize(name); @@ -167,11 +175,11 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { // model name cannot use reserved keyword, e.g. return if(reservedWords.contains(name)) throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); - + // underscore the model file name // PhoneNumber.rb => phone_number.rb return underscore(name); - } + } @Override public String toApiFilename(String name) { @@ -186,7 +194,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { public String toApiName(String name) { if(name.length() == 0) return "DefaultApi"; - // e.g. phone_number_api => PhoneNumberApi + // e.g. phone_number_api => PhoneNumberApi return camelize(name) + "Api"; } @@ -196,8 +204,17 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { if(reservedWords.contains(operationId)) throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); - return underscore(operationId); + return underscore(operationId); } + @Override + public String toModelImport(String name) { + return modelPackage() + "/" + toModelFilename(name); + } + + @Override + public String toApiImport(String name) { + return apiPackage() + "/" + toApiFilename(name); + } } diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index 038a40f66ea..ba38a8157b5 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -1,57 +1,59 @@ require "uri" +module {{moduleName}} {{#operations}} -class {{classname}} - basePath = "{{basePath}}" - # apiInvoker = APIInvoker + class {{classname}} + basePath = "{{basePath}}" + # apiInvoker = APIInvoker {{#operation}} {{newline}} - # {{summary}} - # {{notes}} -{{#allParams}}{{#required}} # @param {{paramName}} {{description}} -{{/required}}{{/allParams}} # @param [Hash] opts the optional parameters -{{#allParams}}{{^required}} # @option opts [{{dataType}}] :{{paramName}} {{description}} -{{/required}}{{/allParams}} # @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} - def self.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {}) - {{#allParams}}{{#required}} - # verify the required parameter '{{paramName}}' is set - raise "Missing the required parameter '{{paramName}}' when calling {{nickname}}" if {{{paramName}}}.nil? - {{/required}}{{/allParams}} + # {{summary}} + # {{notes}} +{{#allParams}}{{#required}} # @param {{paramName}} {{description}} +{{/required}}{{/allParams}} # @param [Hash] opts the optional parameters +{{#allParams}}{{^required}} # @option opts [{{dataType}}] :{{paramName}} {{description}} +{{/required}}{{/allParams}} # @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} + def self.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {}) + {{#allParams}}{{#required}} + # verify the required parameter '{{paramName}}' is set + raise "Missing the required parameter '{{paramName}}' when calling {{nickname}}" if {{{paramName}}}.nil? + {{/required}}{{/allParams}} - # resource path - path = "{{path}}".sub('{format}','json'){{#pathParams}}.sub('{' + '{{baseName}}' + '}', {{paramName}}.to_s){{/pathParams}} + # resource path + path = "{{path}}".sub('{format}','json'){{#pathParams}}.sub('{' + '{{baseName}}' + '}', {{paramName}}.to_s){{/pathParams}} - # query parameters - query_params = {}{{#queryParams}}{{#required}} - query_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/queryParams}}{{#queryParams}}{{^required}} - query_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/queryParams}} + # query parameters + query_params = {}{{#queryParams}}{{#required}} + query_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/queryParams}}{{#queryParams}}{{^required}} + query_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/queryParams}} - # header parameters - header_params = {} + # header parameters + header_params = {} - # 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 + # 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 - # 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[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/headerParams}}{{#headerParams}}{{^required}} - header_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/headerParams}} + # 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[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/headerParams}}{{#headerParams}}{{^required}} + header_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/headerParams}} - # form parameters - form_params = {}{{#formParams}}{{#required}} - form_params["{{baseName}}"] = {{paramName}}{{/required}}{{/formParams}}{{#formParams}}{{^required}} - form_params["{{baseName}}"] = opts[:'{{paramName}}'] if opts[:'{{paramName}}']{{/required}}{{/formParams}} + # form parameters + form_params = {}{{#formParams}}{{#required}} + form_params["{{baseName}}"] = {{paramName}}{{/required}}{{/formParams}}{{#formParams}}{{^required}} + form_params["{{baseName}}"] = opts[:'{{paramName}}'] if opts[:'{{paramName}}']{{/required}}{{/formParams}} - # 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}} + # 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}} - {{#returnType}}response = Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - {{#returnContainer}}response.map {|response| {{/returnContainer}}obj = {{returnBaseType}}.new() and obj.build_from_hash(response){{#returnContainer}} }{{/returnContainer}}{{/returnType}}{{^returnType}} Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make{{/returnType}} + {{#returnType}}response = Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body + {{#returnContainer}}response.map {|response| {{/returnContainer}}obj = {{returnBaseType}}.new() and obj.build_from_hash(response){{#returnContainer}} }{{/returnContainer}}{{/returnType}}{{^returnType}} Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make{{/returnType}} end {{/operation}} -end + end {{/operations}} +end diff --git a/modules/swagger-codegen/src/main/resources/ruby/model.mustache b/modules/swagger-codegen/src/main/resources/ruby/model.mustache index 362664aa2b7..23e589b0862 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/model.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/model.mustache @@ -1,41 +1,42 @@ require_relative 'base_object' -{{#models}}#{{description}} -{{#model}}class {{classname}} < BaseObject - attr_accessor {{#vars}}:{{{name}}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{newline}} - # attribute mapping from ruby-style variable name to JSON key - def self.attribute_map - { - {{#vars}} - # {{description}} - :'{{{name}}}' => :'{{{baseName}}}'{{#hasMore}},{{/hasMore}} - {{/vars}} - } - end - - # attribute type - def self.swagger_types - { - {{#vars}}:'{{{name}}}' => :'{{{datatype}}}'{{#hasMore}},{{/hasMore}} - {{/vars}} - } - end - - def initialize(attributes = {}) - return if !attributes.is_a?(Hash) || attributes.empty? - - # convert string to symbol for hash key - attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} - - {{#vars}} - if attributes[:'{{{baseName}}}'] - {{#isContainer}}if (value = attributes[:'{{{baseName}}}']).is_a?(Array) - @{{{name}}} = value - end{{/isContainer}}{{^isContainer}}@{{{name}}} = attributes[:'{{{baseName}}}']{{/isContainer}} +module {{moduleName}} +{{#models}} # {{description}} +{{#model}} class {{classname}} < BaseObject + attr_accessor {{#vars}}:{{{name}}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{newline}} + # attribute mapping from ruby-style variable name to JSON key + def self.attribute_map + { + {{#vars}} + # {{description}} + :'{{{name}}}' => :'{{{baseName}}}'{{#hasMore}},{{/hasMore}} + {{/vars}} + } end - {{/vars}} - end -end + # attribute type + def self.swagger_types + { + {{#vars}}:'{{{name}}}' => :'{{{datatype}}}'{{#hasMore}},{{/hasMore}} + {{/vars}} + } + end + + def initialize(attributes = {}) + return if !attributes.is_a?(Hash) || attributes.empty? + + # convert string to symbol for hash key + attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + + {{#vars}} + if attributes[:'{{{baseName}}}'] + {{#isContainer}}if (value = attributes[:'{{{baseName}}}']).is_a?(Array) + @{{{name}}} = value + end{{/isContainer}}{{^isContainer}}@{{{name}}} = attributes[:'{{{baseName}}}']{{/isContainer}} + end + {{/vars}} + end + end {{/model}} {{/models}} +end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger-client.gemspec.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger-client.gemspec.mustache index c002e581b8b..d23c4851b24 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger-client.gemspec.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger-client.gemspec.mustache @@ -1,10 +1,10 @@ # -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) -require "swagger/version" +require "{{gemName}}/swagger/version" Gem::Specification.new do |s| - s.name = "{{artifactId}}" - s.version = Swagger::VERSION + s.name = "{{gemName}}" + s.version = {{moduleName}}::Swagger::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Zeke Sikelianos", "Tony Tam"] s.email = ["zeke@wordnik.com", "tony@wordnik.com"] @@ -12,8 +12,6 @@ Gem::Specification.new do |s| s.summary = %q{A ruby wrapper for the swagger APIs} s.description = %q{This gem maps to a swagger API} - s.rubyforge_project = "{{artifactId}}" - s.add_dependency 'typhoeus', '>=0.2.1' s.add_dependency 'addressable', '>=2.2.4' s.add_dependency 'json', '>=1.4.6' diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger-client.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger-client.mustache index b13f83b1dbc..78d45438825 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger-client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger-client.mustache @@ -1,5 +1,26 @@ -require 'monkey' -require 'swagger' +# Swagger common files +require '{{gemName}}/monkey' +require '{{gemName}}/swagger' +require '{{gemName}}/swagger/configuration' +require '{{gemName}}/swagger/request' +require '{{gemName}}/swagger/response' +require '{{gemName}}/swagger/version' -Dir[File.join(File.dirname(__FILE__), "../lib/*.rb")].each {|file| require file if file !~ /swagger-client\.rb\z/ } -Dir[File.join(File.dirname(__FILE__), "../models/*.rb")].each {|file| require file } +# Models +{{#models}} +{{#model}} +require '{{importPath}}' +{{/model}} +{{/models}} + +# APIs +{{#apiInfo}} +{{#apis}} +require '{{importPath}}' +{{/apis}} +{{/apiInfo}} + +module {{moduleName}} + # Initialize the default configuration + Swagger.configuration ||= Swagger::Configuration.new +end \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache index f393330b148..750e6ac5155 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache @@ -1,86 +1,78 @@ -require 'monkey' -require 'swagger/configuration' -require 'swagger/request' -require 'swagger/response' -require 'swagger/version' require 'logger' require 'json' -module Swagger - - @configuration = Configuration.new +module {{moduleName}} + module Swagger + class << self + attr_accessor :logger - 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 + # 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 = '1234567890abcdef' # required - # config.username = 'wordlover' # optional, but needed for user-related functions - # config.password = 'i<3words' # optional, but needed for user-related functions - # config.format = 'json' # optional, defaults to 'json' - # end - # - def configure - yield(configuration) if block_given? + attr_accessor :resources - # Configure logger. Default to use Rails - self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT)) + # Call this method to modify defaults in your initializers. + # + # @example + # Swagger.configure do |config| + # config.api_key = '1234567890abcdef' # required + # config.username = 'wordlover' # optional, but needed for user-related functions + # config.password = 'i<3words' # optional, but needed for user-related functions + # config.format = 'json' # optional, defaults to 'json' + # end + # + def configure + yield(configuration) if block_given? - # remove :// from scheme - configuration.scheme.sub!(/:\/\//, '') + # Configure logger. Default to use Rails + self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT)) - # remove http(s):// and anything after a slash - configuration.host.sub!(/https?:\/\//, '') - configuration.host = configuration.host.split('/').first + # remove :// from scheme + configuration.scheme.sub!(/:\/\//, '') - # 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.present? - end - - def de_authenticate - Swagger.configuration.auth_token = nil - end - - def authenticate - return if Swagger.authenticated? - - if Swagger.configuration.username.blank? || Swagger.configuration.password.blank? - raise ClientError, "Username and password are required to authenticate." + # 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.present? + end + + def de_authenticate + Swagger.configuration.auth_token = nil + end + + def authenticate + return if Swagger.authenticated? + + if Swagger.configuration.username.blank? || Swagger.configuration.password.blank? + raise ClientError, "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 - - 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 - end - -end -class ServerError < StandardError -end + class ServerError < StandardError + end -class ClientError < StandardError + class ClientError < StandardError + 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 index d27109aa445..e780a9c8e7d 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache @@ -1,22 +1,19 @@ -module Swagger - - class Configuration - require 'swagger/version' +module {{moduleName}} + module Swagger + class Configuration + attr_accessor :format, :api_key, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent - attr_accessor :format, :api_key, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent - - # 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 - @camelize_params = true + # 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 + @camelize_params = true + 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 index 4ec071b93d5..14718bb6b3c 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache @@ -1,263 +1,257 @@ -module Swagger +module {{moduleName}} + module Swagger + class Request + require 'uri' + require 'addressable/uri' + require 'typhoeus' - class Request - require 'uri' - require 'addressable/uri' - require 'typhoeus' - require "swagger/version" + attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params - attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params + # All requests must have an HTTP method and a path + # Optionals parameters are :params, :headers, :body, :format, :host + def initialize(http_method, path, attributes={}) + attributes[:format] ||= Swagger.configuration.format + attributes[:params] ||= {} + # Set default headers + default_headers = { + 'Content-Type' => "application/#{attributes[:format].downcase}", + :api_key => Swagger.configuration.api_key, + 'User-Agent' => Swagger.configuration.user_agent + } - # All requests must have an HTTP method and a path - # Optionals parameters are :params, :headers, :body, :format, :host - # - def initialize(http_method, path, attributes={}) - attributes[:format] ||= Swagger.configuration.format - attributes[:params] ||= {} + # api_key from headers hash trumps the default, even if its value is blank + if attributes[:headers].present? && attributes[:headers].has_key?(:api_key) + default_headers.delete(:api_key) + end - # Set default headers - default_headers = { - 'Content-Type' => "application/#{attributes[:format].downcase}", - :api_key => Swagger.configuration.api_key, - 'User-Agent' => Swagger.configuration.user_agent - } + # api_key from params hash trumps all others (headers and default_headers) + if attributes[:params].present? && attributes[:params].has_key?(:api_key) + default_headers.delete(:api_key) + attributes[:headers].delete(:api_key) if attributes[:headers].present? + end - # api_key from headers hash trumps the default, even if its value is blank - if attributes[:headers].present? && attributes[:headers].has_key?(:api_key) - default_headers.delete(:api_key) - end - - # api_key from params hash trumps all others (headers and default_headers) - if attributes[:params].present? && attributes[:params].has_key?(:api_key) - default_headers.delete(:api_key) - attributes[:headers].delete(:api_key) if attributes[:headers].present? - end - - # Merge argument headers into defaults - attributes[:headers] = default_headers.merge(attributes[:headers] || {}) - - # Stick in the auth token if there is one - if Swagger.authenticated? - attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token}) - end - - self.http_method = http_method.to_sym - self.path = path - attributes.each do |name, value| - send("#{name.to_s.underscore.to_sym}=", value) - end - end + # Merge argument headers into defaults + attributes[:headers] = default_headers.merge(attributes[:headers] || {}) - # Construct a base URL - # - def url(options = {}) - u = Addressable::URI.new( - :scheme => Swagger.configuration.scheme, - :host => Swagger.configuration.host, - :path => self.interpreted_path, - :query => self.query_string.sub(/\?/, '') - ).to_s - - # Drop trailing question mark, if present - u.sub! /\?$/, '' - - # Obfuscate API key? - u.sub! /api\_key=\w+/, 'api_key=YOUR_API_KEY' if options[:obfuscated] - - u - end + # Stick in the auth token if there is one + if Swagger.authenticated? + attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token}) + 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}") + self.http_method = http_method.to_sym + self.path = path + attributes.each do |name, value| + send("#{name.to_s.underscore.to_sym}=", value) 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}" + # Construct a base URL + def url(options = {}) + u = Addressable::URI.new( + :scheme => Swagger.configuration.scheme, + :host => Swagger.configuration.host, + :path => self.interpreted_path, + :query => self.query_string.sub(/\?/, '') + ).to_s + + # Drop trailing question mark, if present + u.sub! /\?$/, '' + + # Obfuscate API key? + u.sub! /api\_key=\w+/, 'api_key=YOUR_API_KEY' if options[:obfuscated] + + u + 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 + + # Massage the request body into a state of readiness + # If body is a hash, camelize all keys then convert to a json string + def body=(value) + if value.is_a?(Hash) + value = value.inject({}) do |memo, (k,v)| + memo[k.to_s.camelize(:lower).to_sym] = v + memo + end + end + @body = value + 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 @body.nil? && @form_params && !@form_params.empty? + 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 + data + else # http body is JSON + @body.is_a?(String) ? @body : @body.to_json end end - p = p.sub("{format}", self.format.to_s) - - URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/') - end - - # Massage the request body into a state of readiness - # If body is a hash, camelize all keys then convert to a json string - # - def body=(value) - if value.is_a?(Hash) - value = value.inject({}) do |memo, (k,v)| - memo[k.to_s.camelize(:lower).to_sym] = v - memo + # Construct a query string from the query-string-type params + def query_string + # Iterate over all params, + # .. removing the ones that are part of the path itself. + # .. stringifying values so Addressable doesn't blow up. + query_values = {} + self.params.each_pair do |key, value| + next if self.path.include? "{#{key}}" # skip path params + next if value.blank? && value.class != FalseClass # skip empties + if Swagger.configuration.camelize_params + key = key.to_s.camelize(:lower).to_sym unless key.to_sym == :api_key # api_key is not a camelCased param + end + query_values[key] = value.to_s + end + + # We don't want to end up with '?' as our query string + # if there aren't really any params + return "" if query_values.blank? + + # Addressable requires query_values to be set after initialization.. + qs = Addressable::URI.new + qs.query_values = query_values + qs.to_s + end + + def make + #TODO use configuration setting to determine if debugging + #logger = Logger.new STDOUT + #logger.debug self.url + response = case self.http_method.to_sym + when :get,:GET + Typhoeus::Request.get( + self.url, + :headers => self.headers.stringify_keys, + ) + + when :post,:POST + Typhoeus::Request.post( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + + when :patch,:PATCH + Typhoeus::Request.patch( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + + when :put,:PUT + Typhoeus::Request.put( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + + when :delete,:DELETE + Typhoeus::Request.delete( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + end + Response.new(response) + end + + def response + self.make + end + + def response_code_pretty + return unless @response.present? + @response.code.to_s + end + + def response_headers_pretty + return unless @response.present? + # 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 - @body = value - 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 @body.nil? && @form_params && !@form_params.empty? - data = form_params.dup - data.each do |key, value| - data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter + + # 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 - data - else # http body is JSON - @body.is_a?(String) ? @body : @body.to_json end - end - - # Construct a query string from the query-string-type params - def query_string - # Iterate over all params, - # .. removing the ones that are part of the path itself. - # .. stringifying values so Addressable doesn't blow up. - query_values = {} - self.params.each_pair do |key, value| - next if self.path.include? "{#{key}}" # skip path params - next if value.blank? && value.class != FalseClass # skip empties - if Swagger.configuration.camelize_params - key = key.to_s.camelize(:lower).to_sym unless key.to_sym == :api_key # api_key is not a camelCased param + # 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 - query_values[key] = value.to_s + _body.to_json end - - # We don't want to end up with '?' as our query string - # if there aren't really any params - return "" if query_values.blank? - - # Addressable requires query_values to be set after initialization.. - qs = Addressable::URI.new - qs.query_values = query_values - qs.to_s - end - - def make - #TODO use configuration setting to determine if debugging - #logger = Logger.new STDOUT - #logger.debug self.url - response = case self.http_method.to_sym - when :get,:GET - Typhoeus::Request.get( - self.url, - :headers => self.headers.stringify_keys, - ) - when :post,:POST - Typhoeus::Request.post( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) - - when :patch,:PATCH - Typhoeus::Request.patch( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) - - when :put,:PUT - Typhoeus::Request.put( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) - - when :delete,:DELETE - Typhoeus::Request.delete( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) + # 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 - Response.new(response) - end - - def response - self.make - end - - def response_code_pretty - return unless @response.present? - @response.code.to_s - end - - def response_headers_pretty - return unless @response.present? - # 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/response.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache index 641b7ccc756..e7bb482fb66 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache @@ -1,70 +1,70 @@ -module Swagger +module {{moduleName}} + module Swagger + class Response + require 'json' - class Response - require 'json' + attr_accessor :raw - attr_accessor :raw + def initialize(raw) + self.raw = raw - def initialize(raw) - self.raw = raw + case self.code + when 500..510 then raise(ServerError, self.error_message) + when 299..426 then raise(ClientError, self.error_message) + end + end - case self.code - when 500..510 then raise(ServerError, self.error_message) - when 299..426 then raise(ClientError, self.error_message) + def code + raw.code + end + + # Account for error messages that take different forms... + def error_message + body['message'] + rescue + body + end + + # If body is JSON, parse it + # Otherwise return raw string + def body + JSON.parse(raw.body, :symbolize_names => true) + rescue + raw.body + 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.present? + case format + when 'json' then JSON.pretty_generate(body).gsub(/\n/, '
') + end + end + + def pretty_headers + JSON.pretty_generate(headers).gsub(/\n/, '
') end end - - def code - raw.code - end - - # Account for error messages that take different forms... - def error_message - body['message'] - rescue - body - end - - # If body is JSON, parse it - # Otherwise return raw string - def body - JSON.parse(raw.body, :symbolize_names => true) - rescue - raw.body - 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.present? - case format - when 'json' then JSON.pretty_generate(body).gsub(/\n/, '
') - 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/version.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache index 39357c0ed6d..332a5e66f45 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache @@ -1,4 +1,5 @@ -module Swagger - VERSION = "4.06.08" +module {{moduleName}} + module Swagger + VERSION = "{{appVersion}}" + end end -