Skip to content

Commit

Permalink
[Ruby] Add auto-generated rubocop config file (#7637)
Browse files Browse the repository at this point in the history
* add rubocop to ruby api client

* add new files

* fix ruby generator test case
  • Loading branch information
wing328 authored Feb 12, 2018
1 parent 86697fe commit aa6b217
Show file tree
Hide file tree
Showing 78 changed files with 920 additions and 1,025 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,7 @@ public void processOpts() {
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile("Rakefile.mustache", "", "Rakefile"));
supportingFiles.add(new SupportingFile("Gemfile.mustache", "", "Gemfile"));
supportingFiles.add(new SupportingFile("rubocop.mustache", "", ".rubocop.yml"));

// test files should not be overwritten
writeOptional(outputFolder, new SupportingFile("rspec.mustache", "", ".rspec"));
Expand Down Expand Up @@ -411,7 +412,7 @@ public String toDefaultValue(Property p) {
} else if (p instanceof StringProperty) {
StringProperty sp = (StringProperty) p;
if (sp.getDefault() != null) {
return "\"" + escapeText(sp.getDefault()) + "\"";
return "'" + escapeText(sp.getDefault()) + "'";
}
}

Expand Down Expand Up @@ -565,7 +566,7 @@ public String toEnumValue(String value, String datatype) {
if ("Integer".equals(datatype) || "Float".equals(datatype)) {
return value;
} else {
return "\"" + escapeText(value) + "\"";
return "'" + escapeText(value) + "'";
}
}

Expand Down Expand Up @@ -658,7 +659,7 @@ public void setParameterExampleValue(CodegenParameter p) {
if (example == null) {
example = p.paramName + "_example";
}
example = "\"" + escapeText(example) + "\"";
example = "'" + escapeText(example) + "'";
} else if ("Integer".equals(type)) {
if (example == null) {
example = "56";
Expand All @@ -675,17 +676,17 @@ public void setParameterExampleValue(CodegenParameter p) {
if (example == null) {
example = "/path/to/file";
}
example = "File.new(\"" + escapeText(example) + "\")";
example = "File.new('" + escapeText(example) + "')";
} else if ("Date".equals(type)) {
if (example == null) {
example = "2013-10-20";
}
example = "Date.parse(\"" + escapeText(example) + "\")";
example = "Date.parse('" + escapeText(example) + "')";
} else if ("DateTime".equals(type)) {
if (example == null) {
example = "2013-10-20T19:20:30+01:00";
}
example = "DateTime.parse(\"" + escapeText(example) + "\")";
example = "DateTime.parse('" + escapeText(example) + "')";
} else if (!languageSpecificPrimitives.contains(type)) {
// type is a model class, e.g. User
example = moduleName + "::" + type + ".new";
Expand Down
23 changes: 15 additions & 8 deletions modules/swagger-codegen/src/main/resources/ruby/api.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
{{> api_info}}
=end

require "uri"
require 'uri'

module {{moduleName}}
{{#operations}}
Expand All @@ -13,27 +13,34 @@ module {{moduleName}}
@api_client = api_client
end
{{#operation}}
{{newline}}
{{#summary}}
# {{{summary}}}
{{/summary}}
{{#notes}}
# {{{notes}}}
{{/notes}}
{{#allParams}}{{#required}} # @param {{paramName}} {{description}}
{{/required}}{{/allParams}} # @param [Hash] opts the optional parameters
{{#allParams}}{{^required}} # @option opts [{{{dataType}}}] :{{paramName}} {{description}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}
{{/required}}{{/allParams}} # @return [{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}]
def {{operationId}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {})
{{#returnType}}data, _status_code, _headers = {{/returnType}}{{operationId}}_with_http_info({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts)
{{#returnType}}return data{{/returnType}}{{^returnType}}return nil{{/returnType}}
{{#returnType}}data{{/returnType}}{{^returnType}}nil{{/returnType}}
end

{{#summary}}
# {{summary}}
{{/summary}}
{{#notes}}
# {{notes}}
{{/notes}}
{{#allParams}}{{#required}} # @param {{paramName}} {{description}}
{{/required}}{{/allParams}} # @param [Hash] opts the optional parameters
{{#allParams}}{{^required}} # @option opts [{{{dataType}}}] :{{paramName}} {{description}}
{{/required}}{{/allParams}} # @return [Array<({{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}, Fixnum, Hash)>] {{#returnType}}{{{returnType}}} data{{/returnType}}{{^returnType}}nil{{/returnType}}, response status code and response headers
def {{operationId}}_with_http_info({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug "Calling API: {{classname}}.{{operationId}} ..."
@api_client.config.logger.debug 'Calling API: {{classname}}.{{operationId}} ...'
end
{{#allParams}}
{{#required}}
Expand All @@ -53,7 +60,7 @@ module {{moduleName}}
{{^required}}
{{#isEnum}}
{{#collectionFormat}}
if @api_client.config.client_side_validation && opts[:'{{{paramName}}}'] && !opts[:'{{{paramName}}}'].all?{|item| [{{#allowableValues}}{{#values}}'{{{this}}}'{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}].include?(item)}
if @api_client.config.client_side_validation && opts[:'{{{paramName}}}'] && !opts[:'{{{paramName}}}'].all? { |item| [{{#allowableValues}}{{#values}}'{{{this}}}'{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}].include?(item) }
fail ArgumentError, 'invalid value for "{{{paramName}}}", must include one of {{#allowableValues}}{{#values}}{{{this}}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}'
end
{{/collectionFormat}}
Expand Down Expand Up @@ -110,7 +117,7 @@ module {{moduleName}}
{{/hasValidation}}
{{/allParams}}
# resource path
local_var_path = "{{{path}}}"{{#pathParams}}.sub('{' + '{{baseName}}' + '}', {{paramName}}.to_s){{/pathParams}}
local_var_path = '{{{path}}}'{{#pathParams}}.sub('{' + '{{baseName}}' + '}', {{paramName}}.to_s){{/pathParams}}

# query parameters
query_params = {}
Expand Down Expand Up @@ -150,12 +157,12 @@ module {{moduleName}}
form_params = {}
{{#formParams}}
{{#required}}
form_params["{{baseName}}"] = {{#collectionFormat}}@api_client.build_collection_param({{{paramName}}}, :{{{collectionFormat}}}){{/collectionFormat}}{{^collectionFormat}}{{{paramName}}}{{/collectionFormat}}
form_params['{{baseName}}'] = {{#collectionFormat}}@api_client.build_collection_param({{{paramName}}}, :{{{collectionFormat}}}){{/collectionFormat}}{{^collectionFormat}}{{{paramName}}}{{/collectionFormat}}
{{/required}}
{{/formParams}}
{{#formParams}}
{{^required}}
form_params["{{baseName}}"] = {{#collectionFormat}}@api_client.build_collection_param(opts[:'{{{paramName}}}'], :{{{collectionFormat}}}){{/collectionFormat}}{{^collectionFormat}}opts[:'{{{paramName}}}']{{/collectionFormat}} if !opts[:'{{paramName}}'].nil?
form_params['{{baseName}}'] = {{#collectionFormat}}@api_client.build_collection_param(opts[:'{{{paramName}}}'], :{{{collectionFormat}}}){{/collectionFormat}}{{^collectionFormat}}opts[:'{{{paramName}}}']{{/collectionFormat}} if !opts[:'{{paramName}}'].nil?
{{/required}}
{{/formParams}}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ module {{moduleName}}
@config = config
@user_agent = "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/#{VERSION}/ruby{{/httpUserAgent}}"
@default_headers = {
'Content-Type' => "application/json",
'Content-Type' => 'application/json',
'User-Agent' => @user_agent
}
end
Expand Down Expand Up @@ -131,7 +131,7 @@ module {{moduleName}}
# @param [String] mime MIME
# @return [Boolean] True if the MIME is application/json
def json_mime?(mime)
(mime == "*/*") || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil?
(mime == '*/*') || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil?
end

# Deserialize the response to the given return type.
Expand Down Expand Up @@ -195,12 +195,12 @@ module {{moduleName}}
when /\AArray<(.+)>\z/
# e.g. Array<Pet>
sub_type = $1
data.map {|item| convert_to_type(item, sub_type) }
data.map { |item| convert_to_type(item, sub_type) }
when /\AHash\<String, (.+)\>\z/
# e.g. Hash<String, Integer>
sub_type = $1
{}.tap do |hash|
data.each {|k, v| hash[k] = convert_to_type(v, sub_type) }
data.each { |k, v| hash[k] = convert_to_type(v, sub_type) }
end
else
# models, e.g. Pet
Expand All @@ -222,7 +222,7 @@ module {{moduleName}}
encoding = nil
request.on_headers do |response|
content_disposition = response.headers['Content-Disposition']
if content_disposition and content_disposition =~ /filename=/i
if content_disposition && content_disposition =~ /filename=/i
filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
prefix = sanitize_filename(filename)
else
Expand Down Expand Up @@ -321,7 +321,7 @@ module {{moduleName}}
return nil if accepts.nil? || accepts.empty?
# use JSON when present, otherwise use all of the provided
json_accept = accepts.find { |s| json_mime?(s) }
return json_accept || accepts.join(',')
json_accept || accepts.join(',')
end

# Return Content-Type header based on an array of content types provided.
Expand All @@ -332,7 +332,7 @@ module {{moduleName}}
return 'application/json' if content_types.nil? || content_types.empty?
# use JSON when present, otherwise use the first one
json_content_type = content_types.find { |s| json_mime?(s) }
return json_content_type || content_types.first
json_content_type || content_types.first
end

# Convert object (array, hash, object, etc) to JSON string.
Expand All @@ -342,7 +342,7 @@ module {{moduleName}}
return model if model.nil? || model.is_a?(String)
local_body = nil
if model.is_a?(Array)
local_body = model.map{|m| object_to_hash(m) }
local_body = model.map { |m| object_to_hash(m) }
else
local_body = object_to_hash(model)
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,119 +43,119 @@ describe {{moduleName}}::ApiClient do
end
end

describe "params_encoding in #build_request" do
describe 'params_encoding in #build_request' do
let(:config) { {{moduleName}}::Configuration.new }
let(:api_client) { {{moduleName}}::ApiClient.new(config) }

it "defaults to nil" do
it 'defaults to nil' do
expect({{moduleName}}::Configuration.default.params_encoding).to eq(nil)
expect(config.params_encoding).to eq(nil)

request = api_client.build_request(:get, '/test')
expect(request.options[:params_encoding]).to eq(nil)
end

it "can be customized" do
it 'can be customized' do
config.params_encoding = :multi
request = api_client.build_request(:get, '/test')
expect(request.options[:params_encoding]).to eq(:multi)
end
end

describe "timeout in #build_request" do
describe 'timeout in #build_request' do
let(:config) { {{moduleName}}::Configuration.new }
let(:api_client) { {{moduleName}}::ApiClient.new(config) }

it "defaults to 0" do
it 'defaults to 0' do
expect({{moduleName}}::Configuration.default.timeout).to eq(0)
expect(config.timeout).to eq(0)

request = api_client.build_request(:get, '/test')
expect(request.options[:timeout]).to eq(0)
end

it "can be customized" do
it 'can be customized' do
config.timeout = 100
request = api_client.build_request(:get, '/test')
expect(request.options[:timeout]).to eq(100)
end
end

describe "#deserialize" do
describe '#deserialize' do
it "handles Array<Integer>" do
api_client = {{moduleName}}::ApiClient.new
headers = {'Content-Type' => 'application/json'}
headers = { 'Content-Type' => 'application/json' }
response = double('response', headers: headers, body: '[12, 34]')
data = api_client.deserialize(response, 'Array<Integer>')
expect(data).to be_instance_of(Array)
expect(data).to eq([12, 34])
end

it "handles Array<Array<Integer>>" do
it 'handles Array<Array<Integer>>' do
api_client = {{moduleName}}::ApiClient.new
headers = {'Content-Type' => 'application/json'}
headers = { 'Content-Type' => 'application/json' }
response = double('response', headers: headers, body: '[[12, 34], [56]]')
data = api_client.deserialize(response, 'Array<Array<Integer>>')
expect(data).to be_instance_of(Array)
expect(data).to eq([[12, 34], [56]])
end

it "handles Hash<String, String>" do
it 'handles Hash<String, String>' do
api_client = {{moduleName}}::ApiClient.new
headers = {'Content-Type' => 'application/json'}
headers = { 'Content-Type' => 'application/json' }
response = double('response', headers: headers, body: '{"message": "Hello"}')
data = api_client.deserialize(response, 'Hash<String, String>')
expect(data).to be_instance_of(Hash)
expect(data).to eq({:message => 'Hello'})
expect(data).to eq(:message => 'Hello')
end
end

describe "#object_to_hash" do
it "ignores nils and includes empty arrays" do
it 'ignores nils and includes empty arrays' do
# uncomment below to test object_to_hash for model
#api_client = {{moduleName}}::ApiClient.new
#_model = {{moduleName}}::ModelName.new
# api_client = {{moduleName}}::ApiClient.new
# _model = {{moduleName}}::ModelName.new
# update the model attribute below
#_model.id = 1
# _model.id = 1
# update the expected value (hash) below
#expected = {id: 1, name: '', tags: []}
#expect(api_client.object_to_hash(_model)).to eq(expected)
# expected = {id: 1, name: '', tags: []}
# expect(api_client.object_to_hash(_model)).to eq(expected)
end
end

describe "#build_collection_param" do
describe '#build_collection_param' do
let(:param) { ['aa', 'bb', 'cc'] }
let(:api_client) { {{moduleName}}::ApiClient.new }

it "works for csv" do
it 'works for csv' do
expect(api_client.build_collection_param(param, :csv)).to eq('aa,bb,cc')
end

it "works for ssv" do
it 'works for ssv' do
expect(api_client.build_collection_param(param, :ssv)).to eq('aa bb cc')
end

it "works for tsv" do
it 'works for tsv' do
expect(api_client.build_collection_param(param, :tsv)).to eq("aa\tbb\tcc")
end

it "works for pipes" do
it 'works for pipes' do
expect(api_client.build_collection_param(param, :pipes)).to eq('aa|bb|cc')
end

it "works for multi" do
it 'works for multi' do
expect(api_client.build_collection_param(param, :multi)).to eq(['aa', 'bb', 'cc'])
end

it "fails for invalid collection format" do
it 'fails for invalid collection format' do
expect(proc { api_client.build_collection_param(param, :INVALID) }).to raise_error(RuntimeError, 'unknown collection format: :INVALID')
end
end

describe "#json_mime?" do
describe '#json_mime?' do
let(:api_client) { {{moduleName}}::ApiClient.new }

it "works" do
it 'works' do
expect(api_client.json_mime?(nil)).to eq false
expect(api_client.json_mime?('')).to eq false

Expand All @@ -169,10 +169,10 @@ describe {{moduleName}}::ApiClient do
end
end

describe "#select_header_accept" do
describe '#select_header_accept' do
let(:api_client) { {{moduleName}}::ApiClient.new }

it "works" do
it 'works' do
expect(api_client.select_header_accept(nil)).to be_nil
expect(api_client.select_header_accept([])).to be_nil

Expand All @@ -185,10 +185,10 @@ describe {{moduleName}}::ApiClient do
end
end

describe "#select_header_content_type" do
describe '#select_header_content_type' do
let(:api_client) { {{moduleName}}::ApiClient.new }

it "works" do
it 'works' do
expect(api_client.select_header_content_type(nil)).to eq('application/json')
expect(api_client.select_header_content_type([])).to eq('application/json')

Expand All @@ -200,10 +200,10 @@ describe {{moduleName}}::ApiClient do
end
end

describe "#sanitize_filename" do
describe '#sanitize_filename' do
let(:api_client) { {{moduleName}}::ApiClient.new }

it "works" do
it 'works' do
expect(api_client.sanitize_filename('sun')).to eq('sun')
expect(api_client.sanitize_filename('sun.gif')).to eq('sun.gif')
expect(api_client.sanitize_filename('../sun.gif')).to eq('sun.gif')
Expand Down
Loading

0 comments on commit aa6b217

Please sign in to comment.