Skip to content

[Ruby] Add parameter validation in method call #2697

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 26, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ public class CodegenParameter {
public Map<String, Object> allowableValues;
public CodegenProperty items;
public Map<String, Object> vendorExtensions;
public Boolean hasValidation;

/**
* Determines whether this parameter is mandatory. If the parameter is in "path",
Expand Down Expand Up @@ -120,6 +121,7 @@ public CodegenParameter copy() {
output.items = this.items;
}
output.vendorExtensions = this.vendorExtensions;
output.hasValidation = this.hasValidation;
output.isBinary = this.isBinary;
output.isByteArray = this.isByteArray;
output.isString = this.isString;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ public int hashCode()
result = prime * result + ((setter == null) ? 0 : setter.hashCode());
result = prime * result + ((unescapedDescription == null) ? 0 : unescapedDescription.hashCode());
result = prime * result + ((vendorExtensions == null) ? 0 : vendorExtensions.hashCode());
result = prime * result + ((hasValidation == null) ? 0 : hasValidation.hashCode());
result = prime * result + ((isString == null) ? 0 : isString.hashCode());
result = prime * result + ((isInteger == null) ? 0 : isInteger.hashCode());
result = prime * result + ((isLong == null) ? 0 : isLong.hashCode());
Expand Down Expand Up @@ -203,12 +204,19 @@ public boolean equals(Object obj) {
if (this.allowableValues != other.allowableValues && (this.allowableValues == null || !this.allowableValues.equals(other.allowableValues))) {
return false;
}

if (this.vendorExtensions != other.vendorExtensions && (this.vendorExtensions == null || !this.vendorExtensions.equals(other.vendorExtensions))) {
return false;
}

if (this.hasValidation != other.hasValidation && (this.hasValidation == null || !this.hasValidation.equals(other.hasValidation))) {
return false;
}

if (this.isString != other.isString && (this.isString == null || !this.isString.equals(other.isString))) {
return false;
}

if (this.isInteger != other.isInteger && (this.isInteger == null || !this.isInteger.equals(other.isInteger))) {
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1833,6 +1833,15 @@ public CodegenParameter fromParameter(Parameter param, Set<String> imports) {
p.minItems = qp.getMinItems();
p.uniqueItems = qp.isUniqueItems();
p.multipleOf = qp.getMultipleOf();

if (p.maximum != null || p.exclusiveMaximum != null ||
p.minimum != null || p.exclusiveMinimum != null ||
p.maxLength != null || p.minLength != null ||
p.maxItems != null || p.minItems != null ||
p.pattern != null) {
p.hasValidation = true;
}

} else {
if (!(param instanceof BodyParameter)) {
LOGGER.error("Cannot use Parameter " + param + " as Body Parameter");
Expand Down
56 changes: 48 additions & 8 deletions modules/swagger-codegen/src/main/resources/ruby/api.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -33,19 +33,59 @@ module {{moduleName}}
{{/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}}
{{#allParams}}
{{#required}}
# verify the required parameter '{{paramName}}' is set
fail "Missing the required parameter '{{paramName}}' when calling {{operationId}}" if {{{paramName}}}.nil?{{#isEnum}}
fail ArgumentError, "Missing the required parameter '{{paramName}}' when calling {{classname}}.{{operationId}}" if {{{paramName}}}.nil?
{{#isEnum}}
# verify enum value
unless [{{#allowableValues}}{{#values}}'{{{this}}}'{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}].include?({{{paramName}}})
fail "invalid value for '{{{paramName}}}', must be one of {{#allowableValues}}{{#values}}{{{this}}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}"
end{{/isEnum}}
{{/required}}{{^required}}{{#isEnum}}
fail ArgumentError, "invalid value for '{{{paramName}}}', must be one of {{#allowableValues}}{{#values}}{{{this}}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}"
end
{{/isEnum}}
{{/required}}
{{^required}}
{{#isEnum}}
if opts[:'{{{paramName}}}'] && ![{{#allowableValues}}{{#values}}'{{{this}}}'{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}].include?(opts[:'{{{paramName}}}'])
fail 'invalid value for "{{{paramName}}}", must be one of {{#allowableValues}}{{#values}}{{{this}}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}'
fail ArgumentError, 'invalid value for "{{{paramName}}}", must be one of {{#allowableValues}}{{#values}}{{{this}}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}'
end
{{/isEnum}}
{{/required}}
{{#hasValidation}}
{{#minLength}}
if {{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}.to_s.length > {{{maxLength}}}
fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, the character length must be smaller than or equal to {{{maxLength}}}.'
end

{{/minLength}}
{{#maxLength}}
if {{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}.to_s.length < {{{minLength}}}
fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, the character length must be great than or equal to {{{minLength}}}.'
end

{{/maxLength}}
{{#maximum}}
if {{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}} > {{{maximum}}}
fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{{maximum}}}.'
end
{{/isEnum}}{{/required}}{{/allParams}}

{{/maximum}}
{{#minimum}}
if {{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}} < {{{minimum}}}
fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, must be greater than or equal to {{{minimum}}}.'
end

{{/minimum}}
{{#pattern}}
if {{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}} !~ Regexp.new({{{pattern}}})
fail ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:"{{{paramName}}}"]{{/required}}" when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}.'
end

{{/pattern}}
{{/hasValidation}}
{{/allParams}}
# resource path
local_var_path = "{{path}}".sub('{format}','json'){{#pathParams}}.sub('{' + '{{baseName}}' + '}', {{paramName}}.to_s){{/pathParams}}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -559,6 +559,96 @@ paths:
description: Invalid username supplied
'404':
description: User not found

/fake:
post:
tags:
- fake
summary: Fake endpoint for testing various parameters
description: Fake endpoint for testing various parameters
operationId: testEndpointParameters
produces:
- application/xml
- application/json
parameters:
- name: integer
type: integer
maximum: 100
minimum: 10
in: formData
description: None
- name: int32
type: integer
format: int32
maximum: 200
minimum: 20
in: formData
description: None
- name: int64
type: integer
format: int64
in: formData
description: None
- name: number
maximum: 543.2
minimum: 32.1
in: formData
description: None
required: true
- name: float
type: number
format: float
maximum: 987.6
in: formData
description: None
- name: double
type: number
in: formData
format: double
maximum: 123.4
minimum: 67.8
required: true
description: None
- name: string
type: string
pattern: /[a-z]/i
in: formData
description: None
required: true
- name: byte
type: string
format: byte
in: formData
description: None
required: true
- name: binary
type: string
format: binary
in: formData
description: None
- name: date
type: string
format: date
in: formData
description: None
- name: dateTime
type: string
format: date-time
in: formData
description: None
- name: password
type: string
format: password
maxLength: 64
minLength: 10
in: formData
description: None
responses:
'400':
description: Invalid username supplied
'404':
description: User not found

securityDefinitions:
petstore_auth:
type: oauth2
Expand Down
33 changes: 22 additions & 11 deletions samples/client/petstore/ruby/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/

- API version: 1.0.0
- Package version: 1.0.0
- Build date: 2016-04-25T22:22:56.750+08:00
- Build date: 2016-04-25T23:58:59.140+08:00
- Build package: class io.swagger.codegen.languages.RubyClientCodegen

## Installation
Expand Down Expand Up @@ -55,22 +55,32 @@ Please follow the [installation](#installation) procedure and then run the follo
# Load the gem
require 'petstore'

# Setup authorization
Petstore.configure do |config|
# Configure OAuth2 access token for authorization: petstore_auth
config.access_token = 'YOUR ACCESS TOKEN'
end
api_instance = Petstore::FakeApi.new

number = "number_example" # String | None

double = 1.2 # Float | None

api_instance = Petstore::PetApi.new
string = "string_example" # String | None

body = Petstore::Pet.new # Pet | Pet object that needs to be added to the store
byte = "B" # String | None

opts = {
integer: 56, # Integer | None
int32: 56, # Integer | None
int64: 789, # Integer | None
float: 3.4, # Float | None
binary: "B", # String | None
date: Date.parse("2013-10-20"), # Date | None
date_time: DateTime.parse("2013-10-20T19:20:30+01:00"), # DateTime | None
password: "password_example" # String | None
}

begin
#Add a new pet to the store
api_instance.add_pet(body)
#Fake endpoint for testing various parameters
api_instance.test_endpoint_parameters(number, double, string, byte, opts)
rescue Petstore::ApiError => e
puts "Exception when calling PetApi->add_pet: #{e}"
puts "Exception when calling FakeApi->test_endpoint_parameters: #{e}"
end

```
Expand All @@ -81,6 +91,7 @@ All URIs are relative to *http://petstore.swagger.io/v2*

Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*Petstore::FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters
*Petstore::PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store
*Petstore::PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet
*Petstore::PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status
Expand Down
82 changes: 82 additions & 0 deletions samples/client/petstore/ruby/docs/FakeApi.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# Petstore::FakeApi

All URIs are relative to *http://petstore.swagger.io/v2*

Method | HTTP request | Description
------------- | ------------- | -------------
[**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters


# **test_endpoint_parameters**
> test_endpoint_parameters(number, double, string, byte, opts)

Fake endpoint for testing various parameters

Fake endpoint for testing various parameters

### Example
```ruby
# load the gem
require 'petstore'

api_instance = Petstore::FakeApi.new

number = "number_example" # String | None

double = 1.2 # Float | None

string = "string_example" # String | None

byte = "B" # String | None

opts = {
integer: 56, # Integer | None
int32: 56, # Integer | None
int64: 789, # Integer | None
float: 3.4, # Float | None
binary: "B", # String | None
date: Date.parse("2013-10-20"), # Date | None
date_time: DateTime.parse("2013-10-20T19:20:30+01:00"), # DateTime | None
password: "password_example" # String | None
}

begin
#Fake endpoint for testing various parameters
api_instance.test_endpoint_parameters(number, double, string, byte, opts)
rescue Petstore::ApiError => e
puts "Exception when calling FakeApi->test_endpoint_parameters: #{e}"
end
```

### Parameters

Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**number** | **String**| None |
**double** | **Float**| None |
**string** | **String**| None |
**byte** | **String**| None |
**integer** | **Integer**| None | [optional]
**int32** | **Integer**| None | [optional]
**int64** | **Integer**| None | [optional]
**float** | **Float**| None | [optional]
**binary** | **String**| None | [optional]
**date** | **Date**| None | [optional]
**date_time** | **DateTime**| None | [optional]
**password** | **String**| None | [optional]

### Return type

nil (empty response body)

### Authorization

No authorization required

### HTTP request headers

- **Content-Type**: Not defined
- **Accept**: application/xml, application/json



1 change: 1 addition & 0 deletions samples/client/petstore/ruby/lib/petstore.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
require 'petstore/models/user'

# APIs
require 'petstore/api/fake_api'
require 'petstore/api/pet_api'
require 'petstore/api/store_api'
require 'petstore/api/user_api'
Expand Down
Loading