forked from loafle/openapi-generator-original
Organize generated Ruby code into a module
This commit is contained in:
parent
6a336f2e1e
commit
104bcc1f89
@ -7,10 +7,10 @@ import java.util.*;
|
|||||||
|
|
||||||
public class CodegenModel {
|
public class CodegenModel {
|
||||||
public String parent;
|
public String parent;
|
||||||
public String name, classname, description, classVarName, modelJson;
|
public String name, classname, importPath, description, classVarName, modelJson;
|
||||||
public String defaultValue;
|
public String defaultValue;
|
||||||
public List<CodegenProperty> vars = new ArrayList<CodegenProperty>();
|
public List<CodegenProperty> vars = new ArrayList<CodegenProperty>();
|
||||||
public Set<String> imports = new HashSet<String>();
|
public Set<String> imports = new HashSet<String>();
|
||||||
public Boolean hasVars, emptyVars, hasMoreModels;
|
public Boolean hasVars, emptyVars, hasMoreModels;
|
||||||
public ExternalDocs externalDocs;
|
public ExternalDocs externalDocs;
|
||||||
}
|
}
|
||||||
|
@ -428,6 +428,7 @@ public class DefaultCodegen {
|
|||||||
m.name = name;
|
m.name = name;
|
||||||
m.description = escapeText(model.getDescription());
|
m.description = escapeText(model.getDescription());
|
||||||
m.classname = toModelName(name);
|
m.classname = toModelName(name);
|
||||||
|
m.importPath = toModelImport(name);
|
||||||
m.classVarName = toVarName(name);
|
m.classVarName = toVarName(name);
|
||||||
m.modelJson = Json.pretty(model);
|
m.modelJson = Json.pretty(model);
|
||||||
m.externalDocs = model.getExternalDocs();
|
m.externalDocs = model.getExternalDocs();
|
||||||
|
@ -165,6 +165,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
|
|||||||
operation.putAll(config.additionalProperties());
|
operation.putAll(config.additionalProperties());
|
||||||
operation.put("classname", config.toApiName(tag));
|
operation.put("classname", config.toApiName(tag));
|
||||||
operation.put("classVarName", config.toApiVarName(tag));
|
operation.put("classVarName", config.toApiVarName(tag));
|
||||||
|
operation.put("importPath", config.toApiImport(tag));
|
||||||
|
|
||||||
allOperations.add(new HashMap<String, Object>(operation));
|
allOperations.add(new HashMap<String, Object>(operation));
|
||||||
for (int i = 0; i < allOperations.size(); i++) {
|
for (int i = 0; i < allOperations.size(); i++) {
|
||||||
|
@ -8,10 +8,9 @@ import java.util.*;
|
|||||||
import java.io.File;
|
import java.io.File;
|
||||||
|
|
||||||
public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||||
protected String invokerPackage = "com.wordnik.client";
|
protected String gemName = "swagger-client";
|
||||||
protected String groupId = "com.wordnik";
|
protected String moduleName = null;
|
||||||
protected String artifactId = "swagger-client";
|
protected String libFolder = "lib";
|
||||||
protected String artifactVersion = "1.0.0";
|
|
||||||
|
|
||||||
public CodegenType getTag() {
|
public CodegenType getTag() {
|
||||||
return CodegenType.CLIENT;
|
return CodegenType.CLIENT;
|
||||||
@ -25,10 +24,18 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
|||||||
return "Generates a Ruby client library.";
|
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() {
|
public RubyClientCodegen() {
|
||||||
super();
|
super();
|
||||||
modelPackage = "models";
|
moduleName = generateModuleName();
|
||||||
apiPackage = "lib";
|
modelPackage = gemName + "/models";
|
||||||
|
apiPackage = gemName + "/api";
|
||||||
outputFolder = "generated-code/ruby";
|
outputFolder = "generated-code/ruby";
|
||||||
modelTemplateFiles.put("model.mustache", ".rb");
|
modelTemplateFiles.put("model.mustache", ".rb");
|
||||||
apiTemplateFiles.put("api.mustache", ".rb");
|
apiTemplateFiles.put("api.mustache", ".rb");
|
||||||
@ -39,17 +46,15 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
|||||||
|
|
||||||
reservedWords = new HashSet<String> (
|
reservedWords = new HashSet<String> (
|
||||||
Arrays.asList(
|
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",
|
"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",
|
"else", "for", "nil", "retry", "true", "while", "alias", "class", "elsif",
|
||||||
"if", "not", "return", "undef", "yield")
|
"if", "not", "return", "undef", "yield")
|
||||||
);
|
);
|
||||||
|
|
||||||
additionalProperties.put("invokerPackage", invokerPackage);
|
additionalProperties.put("gemName", gemName);
|
||||||
additionalProperties.put("groupId", groupId);
|
additionalProperties.put("moduleName", moduleName);
|
||||||
additionalProperties.put("artifactId", artifactId);
|
|
||||||
additionalProperties.put("artifactVersion", artifactVersion);
|
|
||||||
|
|
||||||
languageSpecificPrimitives.add("int");
|
languageSpecificPrimitives.add("int");
|
||||||
languageSpecificPrimitives.add("array");
|
languageSpecificPrimitives.add("array");
|
||||||
@ -64,15 +69,18 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
|||||||
typeMapping.put("List", "array");
|
typeMapping.put("List", "array");
|
||||||
typeMapping.put("map", "map");
|
typeMapping.put("map", "map");
|
||||||
|
|
||||||
supportingFiles.add(new SupportingFile("swagger-client.gemspec.mustache", "", "swagger-client.gemspec"));
|
String baseFolder = "lib/" + gemName;
|
||||||
supportingFiles.add(new SupportingFile("swagger-client.mustache", "", "lib/swagger-client.rb"));
|
String swaggerFolder = baseFolder + "/swagger";
|
||||||
supportingFiles.add(new SupportingFile("swagger.mustache", "", "lib/swagger.rb"));
|
String modelFolder = baseFolder + "/models";
|
||||||
supportingFiles.add(new SupportingFile("monkey.mustache", "", "lib/monkey.rb"));
|
supportingFiles.add(new SupportingFile("swagger-client.gemspec.mustache", "", gemName + ".gemspec"));
|
||||||
supportingFiles.add(new SupportingFile("swagger/request.mustache", "", "lib/swagger/request.rb"));
|
supportingFiles.add(new SupportingFile("swagger-client.mustache", "lib", gemName + ".rb"));
|
||||||
supportingFiles.add(new SupportingFile("swagger/response.mustache", "", "lib/swagger/response.rb"));
|
supportingFiles.add(new SupportingFile("monkey.mustache", baseFolder, "monkey.rb"));
|
||||||
supportingFiles.add(new SupportingFile("swagger/version.mustache", "", "lib/swagger/version.rb"));
|
supportingFiles.add(new SupportingFile("swagger.mustache", baseFolder, "swagger.rb"));
|
||||||
supportingFiles.add(new SupportingFile("swagger/configuration.mustache", "", "lib/swagger/configuration.rb"));
|
supportingFiles.add(new SupportingFile("swagger/request.mustache", swaggerFolder, "request.rb"));
|
||||||
supportingFiles.add(new SupportingFile("base_object.mustache", "", "models/base_object.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
|
@Override
|
||||||
@ -82,11 +90,11 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String apiFileFolder() {
|
public String apiFileFolder() {
|
||||||
return outputFolder + "/" + apiPackage().replace('.', File.separatorChar);
|
return outputFolder + File.separatorChar + "lib" + File.separatorChar + gemName + File.separatorChar + "api";
|
||||||
}
|
}
|
||||||
|
|
||||||
public String modelFileFolder() {
|
public String modelFileFolder() {
|
||||||
return outputFolder + "/" + modelPackage().replace('.', File.separatorChar);
|
return outputFolder + File.separatorChar + "lib" + File.separatorChar + gemName + File.separatorChar + "models";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@ -150,13 +158,13 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
|||||||
// should be the same as variable name
|
// should be the same as variable name
|
||||||
return toVarName(name);
|
return toVarName(name);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toModelName(String name) {
|
public String toModelName(String name) {
|
||||||
// model name cannot use reserved keyword, e.g. return
|
// model name cannot use reserved keyword, e.g. return
|
||||||
if(reservedWords.contains(name))
|
if(reservedWords.contains(name))
|
||||||
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
|
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
|
||||||
|
|
||||||
// camelize the model name
|
// camelize the model name
|
||||||
// phone_number => PhoneNumber
|
// phone_number => PhoneNumber
|
||||||
return camelize(name);
|
return camelize(name);
|
||||||
@ -167,11 +175,11 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
|||||||
// model name cannot use reserved keyword, e.g. return
|
// model name cannot use reserved keyword, e.g. return
|
||||||
if(reservedWords.contains(name))
|
if(reservedWords.contains(name))
|
||||||
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
|
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
|
||||||
|
|
||||||
// underscore the model file name
|
// underscore the model file name
|
||||||
// PhoneNumber.rb => phone_number.rb
|
// PhoneNumber.rb => phone_number.rb
|
||||||
return underscore(name);
|
return underscore(name);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toApiFilename(String name) {
|
public String toApiFilename(String name) {
|
||||||
@ -186,7 +194,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
|||||||
public String toApiName(String name) {
|
public String toApiName(String name) {
|
||||||
if(name.length() == 0)
|
if(name.length() == 0)
|
||||||
return "DefaultApi";
|
return "DefaultApi";
|
||||||
// e.g. phone_number_api => PhoneNumberApi
|
// e.g. phone_number_api => PhoneNumberApi
|
||||||
return camelize(name) + "Api";
|
return camelize(name) + "Api";
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -196,8 +204,17 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
|||||||
if(reservedWords.contains(operationId))
|
if(reservedWords.contains(operationId))
|
||||||
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,57 +1,59 @@
|
|||||||
require "uri"
|
require "uri"
|
||||||
|
|
||||||
|
module {{moduleName}}
|
||||||
{{#operations}}
|
{{#operations}}
|
||||||
class {{classname}}
|
class {{classname}}
|
||||||
basePath = "{{basePath}}"
|
basePath = "{{basePath}}"
|
||||||
# apiInvoker = APIInvoker
|
# apiInvoker = APIInvoker
|
||||||
{{#operation}}
|
{{#operation}}
|
||||||
{{newline}}
|
{{newline}}
|
||||||
# {{summary}}
|
# {{summary}}
|
||||||
# {{notes}}
|
# {{notes}}
|
||||||
{{#allParams}}{{#required}} # @param {{paramName}} {{description}}
|
{{#allParams}}{{#required}} # @param {{paramName}} {{description}}
|
||||||
{{/required}}{{/allParams}} # @param [Hash] opts the optional parameters
|
{{/required}}{{/allParams}} # @param [Hash] opts the optional parameters
|
||||||
{{#allParams}}{{^required}} # @option opts [{{dataType}}] :{{paramName}} {{description}}
|
{{#allParams}}{{^required}} # @option opts [{{dataType}}] :{{paramName}} {{description}}
|
||||||
{{/required}}{{/allParams}} # @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
|
{{/required}}{{/allParams}} # @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
|
||||||
def self.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {})
|
def self.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {})
|
||||||
{{#allParams}}{{#required}}
|
{{#allParams}}{{#required}}
|
||||||
# verify the required parameter '{{paramName}}' is set
|
# verify the required parameter '{{paramName}}' is set
|
||||||
raise "Missing the required parameter '{{paramName}}' when calling {{nickname}}" if {{{paramName}}}.nil?
|
raise "Missing the required parameter '{{paramName}}' when calling {{nickname}}" if {{{paramName}}}.nil?
|
||||||
{{/required}}{{/allParams}}
|
{{/required}}{{/allParams}}
|
||||||
|
|
||||||
# resource path
|
# resource path
|
||||||
path = "{{path}}".sub('{format}','json'){{#pathParams}}.sub('{' + '{{baseName}}' + '}', {{paramName}}.to_s){{/pathParams}}
|
path = "{{path}}".sub('{format}','json'){{#pathParams}}.sub('{' + '{{baseName}}' + '}', {{paramName}}.to_s){{/pathParams}}
|
||||||
|
|
||||||
# query parameters
|
# query parameters
|
||||||
query_params = {}{{#queryParams}}{{#required}}
|
query_params = {}{{#queryParams}}{{#required}}
|
||||||
query_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/queryParams}}{{#queryParams}}{{^required}}
|
query_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/queryParams}}{{#queryParams}}{{^required}}
|
||||||
query_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/queryParams}}
|
query_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/queryParams}}
|
||||||
|
|
||||||
# header parameters
|
# header parameters
|
||||||
header_params = {}
|
header_params = {}
|
||||||
|
|
||||||
# HTTP header 'Accept' (if needed)
|
# HTTP header 'Accept' (if needed)
|
||||||
_header_accept = [{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}]
|
_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 = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
|
||||||
|
|
||||||
# HTTP header 'Content-Type'
|
# HTTP header 'Content-Type'
|
||||||
_header_content_type = [{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}]
|
_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'] = Swagger::Request.select_header_content_type(_header_content_type){{#headerParams}}{{#required}}
|
||||||
header_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/headerParams}}{{#headerParams}}{{^required}}
|
header_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/headerParams}}{{#headerParams}}{{^required}}
|
||||||
header_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/headerParams}}
|
header_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/headerParams}}
|
||||||
|
|
||||||
# form parameters
|
# form parameters
|
||||||
form_params = {}{{#formParams}}{{#required}}
|
form_params = {}{{#formParams}}{{#required}}
|
||||||
form_params["{{baseName}}"] = {{paramName}}{{/required}}{{/formParams}}{{#formParams}}{{^required}}
|
form_params["{{baseName}}"] = {{paramName}}{{/required}}{{/formParams}}{{#formParams}}{{^required}}
|
||||||
form_params["{{baseName}}"] = opts[:'{{paramName}}'] if opts[:'{{paramName}}']{{/required}}{{/formParams}}
|
form_params["{{baseName}}"] = opts[:'{{paramName}}'] if opts[:'{{paramName}}']{{/required}}{{/formParams}}
|
||||||
|
|
||||||
# http body (model)
|
# http body (model)
|
||||||
{{^bodyParam}}post_body = nil
|
{{^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 = Swagger::Request.object_to_http_body({{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}})
|
||||||
{{/bodyParam}}
|
{{/bodyParam}}
|
||||||
|
|
||||||
{{#returnType}}response = Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body
|
{{#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}}
|
{{#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
|
end
|
||||||
{{/operation}}
|
{{/operation}}
|
||||||
end
|
end
|
||||||
{{/operations}}
|
{{/operations}}
|
||||||
|
end
|
||||||
|
@ -1,41 +1,42 @@
|
|||||||
require_relative 'base_object'
|
require_relative 'base_object'
|
||||||
|
|
||||||
{{#models}}#{{description}}
|
module {{moduleName}}
|
||||||
{{#model}}class {{classname}} < BaseObject
|
{{#models}} # {{description}}
|
||||||
attr_accessor {{#vars}}:{{{name}}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{newline}}
|
{{#model}} class {{classname}} < BaseObject
|
||||||
# attribute mapping from ruby-style variable name to JSON key
|
attr_accessor {{#vars}}:{{{name}}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{newline}}
|
||||||
def self.attribute_map
|
# attribute mapping from ruby-style variable name to JSON key
|
||||||
{
|
def self.attribute_map
|
||||||
{{#vars}}
|
{
|
||||||
# {{description}}
|
{{#vars}}
|
||||||
:'{{{name}}}' => :'{{{baseName}}}'{{#hasMore}},{{/hasMore}}
|
# {{description}}
|
||||||
{{/vars}}
|
:'{{{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}}
|
|
||||||
end
|
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}}
|
{{/model}}
|
||||||
{{/models}}
|
{{/models}}
|
||||||
|
end
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
# -*- encoding: utf-8 -*-
|
# -*- encoding: utf-8 -*-
|
||||||
$:.push File.expand_path("../lib", __FILE__)
|
$:.push File.expand_path("../lib", __FILE__)
|
||||||
require "swagger/version"
|
require "{{gemName}}/swagger/version"
|
||||||
|
|
||||||
Gem::Specification.new do |s|
|
Gem::Specification.new do |s|
|
||||||
s.name = "{{artifactId}}"
|
s.name = "{{gemName}}"
|
||||||
s.version = Swagger::VERSION
|
s.version = {{moduleName}}::Swagger::VERSION
|
||||||
s.platform = Gem::Platform::RUBY
|
s.platform = Gem::Platform::RUBY
|
||||||
s.authors = ["Zeke Sikelianos", "Tony Tam"]
|
s.authors = ["Zeke Sikelianos", "Tony Tam"]
|
||||||
s.email = ["zeke@wordnik.com", "tony@wordnik.com"]
|
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.summary = %q{A ruby wrapper for the swagger APIs}
|
||||||
s.description = %q{This gem maps to a swagger API}
|
s.description = %q{This gem maps to a swagger API}
|
||||||
|
|
||||||
s.rubyforge_project = "{{artifactId}}"
|
|
||||||
|
|
||||||
s.add_dependency 'typhoeus', '>=0.2.1'
|
s.add_dependency 'typhoeus', '>=0.2.1'
|
||||||
s.add_dependency 'addressable', '>=2.2.4'
|
s.add_dependency 'addressable', '>=2.2.4'
|
||||||
s.add_dependency 'json', '>=1.4.6'
|
s.add_dependency 'json', '>=1.4.6'
|
||||||
|
@ -1,5 +1,26 @@
|
|||||||
require 'monkey'
|
# Swagger common files
|
||||||
require 'swagger'
|
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/ }
|
# Models
|
||||||
Dir[File.join(File.dirname(__FILE__), "../models/*.rb")].each {|file| require file }
|
{{#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
|
@ -1,86 +1,78 @@
|
|||||||
require 'monkey'
|
|
||||||
require 'swagger/configuration'
|
|
||||||
require 'swagger/request'
|
|
||||||
require 'swagger/response'
|
|
||||||
require 'swagger/version'
|
|
||||||
require 'logger'
|
require 'logger'
|
||||||
require 'json'
|
require 'json'
|
||||||
|
|
||||||
module Swagger
|
module {{moduleName}}
|
||||||
|
module Swagger
|
||||||
@configuration = Configuration.new
|
class << self
|
||||||
|
attr_accessor :logger
|
||||||
|
|
||||||
class << self
|
# A Swagger configuration object. Must act like a hash and return sensible
|
||||||
attr_accessor :logger
|
# 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
|
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?
|
|
||||||
|
|
||||||
# Configure logger. Default to use Rails
|
# Call this method to modify defaults in your initializers.
|
||||||
self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT))
|
#
|
||||||
|
# @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
|
# Configure logger. Default to use Rails
|
||||||
configuration.scheme.sub!(/:\/\//, '')
|
self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT))
|
||||||
|
|
||||||
# remove http(s):// and anything after a slash
|
# remove :// from scheme
|
||||||
configuration.host.sub!(/https?:\/\//, '')
|
configuration.scheme.sub!(/:\/\//, '')
|
||||||
configuration.host = configuration.host.split('/').first
|
|
||||||
|
|
||||||
# Add leading and trailing slashes to base_path
|
# remove http(s):// and anything after a slash
|
||||||
configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/')
|
configuration.host.sub!(/https?:\/\//, '')
|
||||||
configuration.base_path = "" if configuration.base_path == "/"
|
configuration.host = configuration.host.split('/').first
|
||||||
end
|
|
||||||
|
# Add leading and trailing slashes to base_path
|
||||||
def authenticated?
|
configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/')
|
||||||
Swagger.configuration.auth_token.present?
|
configuration.base_path = "" if configuration.base_path == "/"
|
||||||
end
|
end
|
||||||
|
|
||||||
def de_authenticate
|
def authenticated?
|
||||||
Swagger.configuration.auth_token = nil
|
Swagger.configuration.auth_token.present?
|
||||||
end
|
end
|
||||||
|
|
||||||
def authenticate
|
def de_authenticate
|
||||||
return if Swagger.authenticated?
|
Swagger.configuration.auth_token = nil
|
||||||
|
end
|
||||||
if Swagger.configuration.username.blank? || Swagger.configuration.password.blank?
|
|
||||||
raise ClientError, "Username and password are required to authenticate."
|
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
|
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
|
end
|
||||||
|
|
||||||
end
|
|
||||||
|
|
||||||
class ServerError < StandardError
|
class ServerError < StandardError
|
||||||
end
|
end
|
||||||
|
|
||||||
class ClientError < StandardError
|
class ClientError < StandardError
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
@ -1,22 +1,19 @@
|
|||||||
module Swagger
|
module {{moduleName}}
|
||||||
|
module Swagger
|
||||||
class Configuration
|
class Configuration
|
||||||
require 'swagger/version'
|
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
|
||||||
# Defaults go in here..
|
@format = 'json'
|
||||||
def initialize
|
@scheme = '{{scheme}}'
|
||||||
@format = 'json'
|
@host = '{{host}}'
|
||||||
@scheme = '{{scheme}}'
|
@base_path = '{{contextPath}}'
|
||||||
@host = '{{host}}'
|
@user_agent = "ruby-swagger-#{Swagger::VERSION}"
|
||||||
@base_path = '{{contextPath}}'
|
@inject_format = false
|
||||||
@user_agent = "ruby-swagger-#{Swagger::VERSION}"
|
@force_ending_format = false
|
||||||
@inject_format = false
|
@camelize_params = true
|
||||||
@force_ending_format = false
|
end
|
||||||
@camelize_params = true
|
|
||||||
end
|
end
|
||||||
|
|
||||||
end
|
end
|
||||||
|
|
||||||
end
|
end
|
||||||
|
@ -1,263 +1,257 @@
|
|||||||
module Swagger
|
module {{moduleName}}
|
||||||
|
module Swagger
|
||||||
|
class Request
|
||||||
|
require 'uri'
|
||||||
|
require 'addressable/uri'
|
||||||
|
require 'typhoeus'
|
||||||
|
|
||||||
class Request
|
attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params
|
||||||
require 'uri'
|
|
||||||
require 'addressable/uri'
|
|
||||||
require 'typhoeus'
|
|
||||||
require "swagger/version"
|
|
||||||
|
|
||||||
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
|
# api_key from headers hash trumps the default, even if its value is blank
|
||||||
# Optionals parameters are :params, :headers, :body, :format, :host
|
if attributes[:headers].present? && attributes[:headers].has_key?(:api_key)
|
||||||
#
|
default_headers.delete(:api_key)
|
||||||
def initialize(http_method, path, attributes={})
|
end
|
||||||
attributes[:format] ||= Swagger.configuration.format
|
|
||||||
attributes[:params] ||= {}
|
|
||||||
|
|
||||||
# Set default headers
|
# api_key from params hash trumps all others (headers and default_headers)
|
||||||
default_headers = {
|
if attributes[:params].present? && attributes[:params].has_key?(:api_key)
|
||||||
'Content-Type' => "application/#{attributes[:format].downcase}",
|
default_headers.delete(:api_key)
|
||||||
:api_key => Swagger.configuration.api_key,
|
attributes[:headers].delete(:api_key) if attributes[:headers].present?
|
||||||
'User-Agent' => Swagger.configuration.user_agent
|
end
|
||||||
}
|
|
||||||
|
|
||||||
# api_key from headers hash trumps the default, even if its value is blank
|
# Merge argument headers into defaults
|
||||||
if attributes[:headers].present? && attributes[:headers].has_key?(:api_key)
|
attributes[:headers] = default_headers.merge(attributes[:headers] || {})
|
||||||
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
|
|
||||||
|
|
||||||
# Construct a base URL
|
# Stick in the auth token if there is one
|
||||||
#
|
if Swagger.authenticated?
|
||||||
def url(options = {})
|
attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token})
|
||||||
u = Addressable::URI.new(
|
end
|
||||||
: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
|
self.http_method = http_method.to_sym
|
||||||
#
|
self.path = path
|
||||||
# e.g. /word.{format}/{word}/entries => /word.json/cat/entries
|
attributes.each do |name, value|
|
||||||
def interpreted_path
|
send("#{name.to_s.underscore.to_sym}=", value)
|
||||||
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
|
||||||
end
|
end
|
||||||
|
|
||||||
# Stick a .{format} placeholder on the end of the path if there isn't
|
# Construct a base URL
|
||||||
# one already or an actual format like json or xml
|
def url(options = {})
|
||||||
# e.g. /words/blah => /words/blah.{format}
|
u = Addressable::URI.new(
|
||||||
if Swagger.configuration.force_ending_format
|
:scheme => Swagger.configuration.scheme,
|
||||||
unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s }
|
:host => Swagger.configuration.host,
|
||||||
p = "#{p}.#{format}"
|
: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
|
||||||
end
|
end
|
||||||
|
|
||||||
p = p.sub("{format}", self.format.to_s)
|
# Construct a query string from the query-string-type params
|
||||||
|
def query_string
|
||||||
URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/')
|
# Iterate over all params,
|
||||||
end
|
# .. removing the ones that are part of the path itself.
|
||||||
|
# .. stringifying values so Addressable doesn't blow up.
|
||||||
# Massage the request body into a state of readiness
|
query_values = {}
|
||||||
# If body is a hash, camelize all keys then convert to a json string
|
self.params.each_pair do |key, value|
|
||||||
#
|
next if self.path.include? "{#{key}}" # skip path params
|
||||||
def body=(value)
|
next if value.blank? && value.class != FalseClass # skip empties
|
||||||
if value.is_a?(Hash)
|
if Swagger.configuration.camelize_params
|
||||||
value = value.inject({}) do |memo, (k,v)|
|
key = key.to_s.camelize(:lower).to_sym unless key.to_sym == :api_key # api_key is not a camelCased param
|
||||||
memo[k.to_s.camelize(:lower).to_sym] = v
|
end
|
||||||
memo
|
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/, '<br/>') # <- This was for RestClient
|
||||||
|
@response.headers.gsub(/\n/, '<br/>') # <- 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
|
||||||
end
|
end
|
||||||
@body = value
|
|
||||||
end
|
# return the content type based on an array of content-type provided
|
||||||
|
# @param [Array] content_type_array Array fo content-type
|
||||||
# If body is an object, JSONify it before making the actual request.
|
# @return String Content-Type (e.g. application/json)
|
||||||
# For form parameters, remove empty value
|
def self.select_header_content_type content_type_array
|
||||||
def outgoing_body
|
if content_type_array.empty?
|
||||||
# http form
|
'application/json' # use application/json by default
|
||||||
if @body.nil? && @form_params && !@form_params.empty?
|
elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 }
|
||||||
data = form_params.dup
|
'application/json' # use application/json if it's included
|
||||||
data.each do |key, value|
|
else
|
||||||
data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter
|
content_type_array[0]; # otherwise, use the first one
|
||||||
end
|
end
|
||||||
data
|
|
||||||
else # http body is JSON
|
|
||||||
@body.is_a?(String) ? @body : @body.to_json
|
|
||||||
end
|
end
|
||||||
end
|
|
||||||
|
|
||||||
# Construct a query string from the query-string-type params
|
|
||||||
def query_string
|
|
||||||
|
|
||||||
# Iterate over all params,
|
# static method to convert object (array, hash, object, etc) to JSON string
|
||||||
# .. removing the ones that are part of the path itself.
|
# @param model object to be converted into JSON string
|
||||||
# .. stringifying values so Addressable doesn't blow up.
|
# @return string JSON string representation of the object
|
||||||
query_values = {}
|
def self.object_to_http_body model
|
||||||
self.params.each_pair do |key, value|
|
return if model.nil?
|
||||||
next if self.path.include? "{#{key}}" # skip path params
|
_body = nil
|
||||||
next if value.blank? && value.class != FalseClass # skip empties
|
if model.is_a?(Array)
|
||||||
if Swagger.configuration.camelize_params
|
_body = model.map{|m| object_to_hash(m) }
|
||||||
key = key.to_s.camelize(:lower).to_sym unless key.to_sym == :api_key # api_key is not a camelCased param
|
else
|
||||||
|
_body = object_to_hash(model)
|
||||||
end
|
end
|
||||||
query_values[key] = value.to_s
|
_body.to_json
|
||||||
end
|
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
|
# static method to convert object(non-array) to hash
|
||||||
Typhoeus::Request.post(
|
# @param obj object to be converted into JSON string
|
||||||
self.url,
|
# @return string JSON string representation of the object
|
||||||
:body => self.outgoing_body,
|
def self.object_to_hash obj
|
||||||
:headers => self.headers.stringify_keys,
|
if obj.respond_to?(:to_hash)
|
||||||
)
|
obj.to_hash
|
||||||
|
else
|
||||||
when :patch,:PATCH
|
obj
|
||||||
Typhoeus::Request.patch(
|
end
|
||||||
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
|
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/, '<br/>') # <- This was for RestClient
|
|
||||||
@response.headers.gsub(/\n/, '<br/>') # <- 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
|
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
|
end
|
||||||
|
@ -1,70 +1,70 @@
|
|||||||
module Swagger
|
module {{moduleName}}
|
||||||
|
module Swagger
|
||||||
|
class Response
|
||||||
|
require 'json'
|
||||||
|
|
||||||
class Response
|
attr_accessor :raw
|
||||||
require 'json'
|
|
||||||
|
|
||||||
attr_accessor :raw
|
def initialize(raw)
|
||||||
|
self.raw = raw
|
||||||
|
|
||||||
def initialize(raw)
|
case self.code
|
||||||
self.raw = raw
|
when 500..510 then raise(ServerError, self.error_message)
|
||||||
|
when 299..426 then raise(ClientError, self.error_message)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
case self.code
|
def code
|
||||||
when 500..510 then raise(ServerError, self.error_message)
|
raw.code
|
||||||
when 299..426 then raise(ClientError, self.error_message)
|
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/, '<br/>')
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def pretty_headers
|
||||||
|
JSON.pretty_generate(headers).gsub(/\n/, '<br/>')
|
||||||
end
|
end
|
||||||
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/, '<br/>')
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
def pretty_headers
|
|
||||||
JSON.pretty_generate(headers).gsub(/\n/, '<br/>')
|
|
||||||
end
|
|
||||||
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
module Swagger
|
module {{moduleName}}
|
||||||
VERSION = "4.06.08"
|
module Swagger
|
||||||
|
VERSION = "{{appVersion}}"
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user