[Ruby] add property, parameter name mapping (#16191)

* add property, parameter name mapping support to ruby generators

* update samples
This commit is contained in:
William Cheng 2023-07-27 09:48:53 +08:00 committed by GitHub
parent 90eacb685c
commit d7311cd5cd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 535 additions and 1 deletions

View File

@ -9,3 +9,9 @@ additionalProperties:
gemName: petstore gemName: petstore
skipFormModel: "true" skipFormModel: "true"
strictSpecBehavior: false strictSpecBehavior: false
nameMappings:
_type: underscore_type
type_: type_with_underscore
parameterNameMappings:
_type: underscore_type
type_: type_with_underscore

View File

@ -176,6 +176,11 @@ abstract public class AbstractRubyCodegen extends DefaultCodegen implements Code
@Override @Override
public String toVarName(final String name) { public String toVarName(final String name) {
// obtain the name from nameMapping directly if provided
if (nameMapping.containsKey(name)) {
return nameMapping.get(name);
}
String varName = sanitizeName(name); String varName = sanitizeName(name);
// if it's all upper case, convert to lower case // if it's all upper case, convert to lower case
if (name.matches("^[A-Z_]*$")) { if (name.matches("^[A-Z_]*$")) {
@ -201,6 +206,11 @@ abstract public class AbstractRubyCodegen extends DefaultCodegen implements Code
@Override @Override
public String toParamName(String name) { public String toParamName(String name) {
// obtain the name from parameterNameMapping directly if provided
if (parameterNameMapping.containsKey(name)) {
return parameterNameMapping.get(name);
}
// should be the same as variable name // should be the same as variable name
return toVarName(name); return toVarName(name);
} }
@ -265,5 +275,7 @@ abstract public class AbstractRubyCodegen extends DefaultCodegen implements Code
} }
@Override @Override
public GeneratorLanguage generatorLanguage() { return GeneratorLanguage.RUBY; } public GeneratorLanguage generatorLanguage() {
return GeneratorLanguage.RUBY;
}
} }

View File

@ -1267,6 +1267,41 @@ paths:
responses: responses:
200: 200:
description: The instance started successfully description: The instance started successfully
/fake/parameter-name-mapping:
get:
tags:
- fake
summary: parameter name mapping test
operationId: getParameterNameMapping
parameters:
- name: _type
in: header
description: _type
required: true
schema:
type: integer
format: int64
- name: type
in: query
description: type
required: true
schema:
type: string
- name: type_
in: header
description: type_
required: true
schema:
type: string
- name: http_debug_option
in: query
description: http debug option (to test parameter naming option)
required: true
schema:
type: string
responses:
200:
description: OK
servers: servers:
- url: 'http://{server}.swagger.io:{port}/v2' - url: 'http://{server}.swagger.io:{port}/v2'
description: petstore server description: petstore server
@ -2045,3 +2080,13 @@ components:
required: required:
- classname - classname
additionalProperties: true additionalProperties: true
PropertyNameMapping:
properties:
http_debug_operation:
type: string
_type:
type: string
type:
type: string
type_:
type: string

View File

@ -56,6 +56,7 @@ docs/OuterEnumIntegerDefaultValue.md
docs/OuterObjectWithEnumProperty.md docs/OuterObjectWithEnumProperty.md
docs/Pet.md docs/Pet.md
docs/PetApi.md docs/PetApi.md
docs/PropertyNameMapping.md
docs/ReadOnlyFirst.md docs/ReadOnlyFirst.md
docs/SingleRefType.md docs/SingleRefType.md
docs/SpecialModelName.md docs/SpecialModelName.md
@ -122,6 +123,7 @@ lib/petstore/models/outer_enum_integer.rb
lib/petstore/models/outer_enum_integer_default_value.rb lib/petstore/models/outer_enum_integer_default_value.rb
lib/petstore/models/outer_object_with_enum_property.rb lib/petstore/models/outer_object_with_enum_property.rb
lib/petstore/models/pet.rb lib/petstore/models/pet.rb
lib/petstore/models/property_name_mapping.rb
lib/petstore/models/read_only_first.rb lib/petstore/models/read_only_first.rb
lib/petstore/models/single_ref_type.rb lib/petstore/models/single_ref_type.rb
lib/petstore/models/special_model_name.rb lib/petstore/models/special_model_name.rb

View File

@ -85,6 +85,7 @@ Class | Method | HTTP request | Description
*Petstore::FakeApi* | [**fake_outer_number_serialize**](docs/FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | *Petstore::FakeApi* | [**fake_outer_number_serialize**](docs/FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number |
*Petstore::FakeApi* | [**fake_outer_string_serialize**](docs/FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | *Petstore::FakeApi* | [**fake_outer_string_serialize**](docs/FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string |
*Petstore::FakeApi* | [**fake_property_enum_integer_serialize**](docs/FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | *Petstore::FakeApi* | [**fake_property_enum_integer_serialize**](docs/FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int |
*Petstore::FakeApi* | [**get_parameter_name_mapping**](docs/FakeApi.md#get_parameter_name_mapping) | **GET** /fake/parameter-name-mapping | parameter name mapping test
*Petstore::FakeApi* | [**test_body_with_binary**](docs/FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | *Petstore::FakeApi* | [**test_body_with_binary**](docs/FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary |
*Petstore::FakeApi* | [**test_body_with_file_schema**](docs/FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | *Petstore::FakeApi* | [**test_body_with_file_schema**](docs/FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema |
*Petstore::FakeApi* | [**test_body_with_query_params**](docs/FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | *Petstore::FakeApi* | [**test_body_with_query_params**](docs/FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params |
@ -166,6 +167,7 @@ Class | Method | HTTP request | Description
- [Petstore::OuterEnumIntegerDefaultValue](docs/OuterEnumIntegerDefaultValue.md) - [Petstore::OuterEnumIntegerDefaultValue](docs/OuterEnumIntegerDefaultValue.md)
- [Petstore::OuterObjectWithEnumProperty](docs/OuterObjectWithEnumProperty.md) - [Petstore::OuterObjectWithEnumProperty](docs/OuterObjectWithEnumProperty.md)
- [Petstore::Pet](docs/Pet.md) - [Petstore::Pet](docs/Pet.md)
- [Petstore::PropertyNameMapping](docs/PropertyNameMapping.md)
- [Petstore::ReadOnlyFirst](docs/ReadOnlyFirst.md) - [Petstore::ReadOnlyFirst](docs/ReadOnlyFirst.md)
- [Petstore::SingleRefType](docs/SingleRefType.md) - [Petstore::SingleRefType](docs/SingleRefType.md)
- [Petstore::SpecialModelName](docs/SpecialModelName.md) - [Petstore::SpecialModelName](docs/SpecialModelName.md)

View File

@ -12,6 +12,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2*
| [**fake_outer_number_serialize**](FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | | | [**fake_outer_number_serialize**](FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | |
| [**fake_outer_string_serialize**](FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | | | [**fake_outer_string_serialize**](FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | |
| [**fake_property_enum_integer_serialize**](FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | | | [**fake_property_enum_integer_serialize**](FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | |
| [**get_parameter_name_mapping**](FakeApi.md#get_parameter_name_mapping) | **GET** /fake/parameter-name-mapping | parameter name mapping test |
| [**test_body_with_binary**](FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | | | [**test_body_with_binary**](FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | |
| [**test_body_with_file_schema**](FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | | | [**test_body_with_file_schema**](FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | |
| [**test_body_with_query_params**](FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | | | [**test_body_with_query_params**](FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | |
@ -542,6 +543,73 @@ No authorization required
- **Accept**: */* - **Accept**: */*
## get_parameter_name_mapping
> get_parameter_name_mapping(underscore_type, type, type_with_underscore, http_debug_option)
parameter name mapping test
### Examples
```ruby
require 'time'
require 'petstore'
api_instance = Petstore::FakeApi.new
underscore_type = 789 # Integer | _type
type = 'type_example' # String | type
type_with_underscore = 'type_with_underscore_example' # String | type_
http_debug_option = 'http_debug_option_example' # String | http debug option (to test parameter naming option)
begin
# parameter name mapping test
api_instance.get_parameter_name_mapping(underscore_type, type, type_with_underscore, http_debug_option)
rescue Petstore::ApiError => e
puts "Error when calling FakeApi->get_parameter_name_mapping: #{e}"
end
```
#### Using the get_parameter_name_mapping_with_http_info variant
This returns an Array which contains the response data (`nil` in this case), status code and headers.
> <Array(nil, Integer, Hash)> get_parameter_name_mapping_with_http_info(underscore_type, type, type_with_underscore, http_debug_option)
```ruby
begin
# parameter name mapping test
data, status_code, headers = api_instance.get_parameter_name_mapping_with_http_info(underscore_type, type, type_with_underscore, http_debug_option)
p status_code # => 2xx
p headers # => { ... }
p data # => nil
rescue Petstore::ApiError => e
puts "Error when calling FakeApi->get_parameter_name_mapping_with_http_info: #{e}"
end
```
### Parameters
| Name | Type | Description | Notes |
| ---- | ---- | ----------- | ----- |
| **underscore_type** | **Integer** | _type | |
| **type** | **String** | type | |
| **type_with_underscore** | **String** | type_ | |
| **http_debug_option** | **String** | http debug option (to test parameter naming option) | |
### Return type
nil (empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
## test_body_with_binary ## test_body_with_binary
> test_body_with_binary(body) > test_body_with_binary(body)

View File

@ -0,0 +1,24 @@
# Petstore::PropertyNameMapping
## Properties
| Name | Type | Description | Notes |
| ---- | ---- | ----------- | ----- |
| **http_debug_operation** | **String** | | [optional] |
| **underscore_type** | **String** | | [optional] |
| **type** | **String** | | [optional] |
| **type_with_underscore** | **String** | | [optional] |
## Example
```ruby
require 'petstore'
instance = Petstore::PropertyNameMapping.new(
http_debug_operation: null,
underscore_type: null,
type: null,
type_with_underscore: null
)
```

View File

@ -60,6 +60,7 @@ require 'petstore/models/outer_enum_integer'
require 'petstore/models/outer_enum_integer_default_value' require 'petstore/models/outer_enum_integer_default_value'
require 'petstore/models/outer_object_with_enum_property' require 'petstore/models/outer_object_with_enum_property'
require 'petstore/models/pet' require 'petstore/models/pet'
require 'petstore/models/property_name_mapping'
require 'petstore/models/read_only_first' require 'petstore/models/read_only_first'
require 'petstore/models/single_ref_type' require 'petstore/models/single_ref_type'
require 'petstore/models/special_model_name' require 'petstore/models/special_model_name'

View File

@ -513,6 +513,87 @@ module Petstore
return data, status_code, headers return data, status_code, headers
end end
# parameter name mapping test
# @param underscore_type [Integer] _type
# @param type [String] type
# @param type_with_underscore [String] type_
# @param http_debug_option [String] http debug option (to test parameter naming option)
# @param [Hash] opts the optional parameters
# @return [nil]
def get_parameter_name_mapping(underscore_type, type, type_with_underscore, http_debug_option, opts = {})
get_parameter_name_mapping_with_http_info(underscore_type, type, type_with_underscore, http_debug_option, opts)
nil
end
# parameter name mapping test
# @param underscore_type [Integer] _type
# @param type [String] type
# @param type_with_underscore [String] type_
# @param http_debug_option [String] http debug option (to test parameter naming option)
# @param [Hash] opts the optional parameters
# @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers
def get_parameter_name_mapping_with_http_info(underscore_type, type, type_with_underscore, http_debug_option, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: FakeApi.get_parameter_name_mapping ...'
end
# verify the required parameter 'underscore_type' is set
if @api_client.config.client_side_validation && underscore_type.nil?
fail ArgumentError, "Missing the required parameter 'underscore_type' when calling FakeApi.get_parameter_name_mapping"
end
# verify the required parameter 'type' is set
if @api_client.config.client_side_validation && type.nil?
fail ArgumentError, "Missing the required parameter 'type' when calling FakeApi.get_parameter_name_mapping"
end
# verify the required parameter 'type_with_underscore' is set
if @api_client.config.client_side_validation && type_with_underscore.nil?
fail ArgumentError, "Missing the required parameter 'type_with_underscore' when calling FakeApi.get_parameter_name_mapping"
end
# verify the required parameter 'http_debug_option' is set
if @api_client.config.client_side_validation && http_debug_option.nil?
fail ArgumentError, "Missing the required parameter 'http_debug_option' when calling FakeApi.get_parameter_name_mapping"
end
# resource path
local_var_path = '/fake/parameter-name-mapping'
# query parameters
query_params = opts[:query_params] || {}
query_params[:'type'] = type
query_params[:'http_debug_option'] = http_debug_option
# header parameters
header_params = opts[:header_params] || {}
header_params[:'_type'] = underscore_type
header_params[:'type_'] = type_with_underscore
# form parameters
form_params = opts[:form_params] || {}
# http body (model)
post_body = opts[:debug_body]
# return_type
return_type = opts[:debug_return_type]
# auth_names
auth_names = opts[:debug_auth_names] || []
new_options = opts.merge(
:operation => :"FakeApi.get_parameter_name_mapping",
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => return_type
)
data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: FakeApi#get_parameter_name_mapping\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# For this test, the body has to be a binary file. # For this test, the body has to be a binary file.
# @param body [File] image to upload # @param body [File] image to upload
# @param [Hash] opts the optional parameters # @param [Hash] opts the optional parameters

View File

@ -0,0 +1,241 @@
=begin
#OpenAPI Petstore
#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 7.0.0-SNAPSHOT
=end
require 'date'
require 'time'
module Petstore
class PropertyNameMapping
attr_accessor :http_debug_operation
attr_accessor :underscore_type
attr_accessor :type
attr_accessor :type_with_underscore
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'http_debug_operation' => :'http_debug_operation',
:'underscore_type' => :'_type',
:'type' => :'type',
:'type_with_underscore' => :'type_'
}
end
# Returns all the JSON keys this model knows about
def self.acceptable_attributes
attribute_map.values
end
# Attribute type mapping.
def self.openapi_types
{
:'http_debug_operation' => :'String',
:'underscore_type' => :'String',
:'type' => :'String',
:'type_with_underscore' => :'String'
}
end
# List of attributes with nullable: true
def self.openapi_nullable
Set.new([
])
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
if (!attributes.is_a?(Hash))
fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::PropertyNameMapping` initialize method"
end
# check to see if the attribute exists and convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h|
if (!self.class.attribute_map.key?(k.to_sym))
fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::PropertyNameMapping`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
end
h[k.to_sym] = v
}
if attributes.key?(:'http_debug_operation')
self.http_debug_operation = attributes[:'http_debug_operation']
end
if attributes.key?(:'underscore_type')
self.underscore_type = attributes[:'underscore_type']
end
if attributes.key?(:'type')
self.type = attributes[:'type']
end
if attributes.key?(:'type_with_underscore')
self.type_with_underscore = attributes[:'type_with_underscore']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
warn '[DEPRECATED] the `list_invalid_properties` method is obsolete'
invalid_properties = Array.new
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
warn '[DEPRECATED] the `valid?` method is obsolete'
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
http_debug_operation == o.http_debug_operation &&
underscore_type == o.underscore_type &&
type == o.type &&
type_with_underscore == o.type_with_underscore
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Integer] Hash code
def hash
[http_debug_operation, underscore_type, type, type_with_underscore].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def self.build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
attributes = attributes.transform_keys(&:to_sym)
transformed_hash = {}
openapi_types.each_pair do |key, type|
if attributes.key?(attribute_map[key]) && attributes[attribute_map[key]].nil?
transformed_hash["#{key}"] = nil
elsif type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[attribute_map[key]].is_a?(Array)
transformed_hash["#{key}"] = attributes[attribute_map[key]].map { |v| _deserialize($1, v) }
end
elsif !attributes[attribute_map[key]].nil?
transformed_hash["#{key}"] = _deserialize(type, attributes[attribute_map[key]])
end
end
new(transformed_hash)
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def self._deserialize(type, value)
case type.to_sym
when :Time
Time.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :Boolean
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
# models (e.g. Pet) or oneOf
klass = Petstore.const_get(type)
klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
if value.nil?
is_nullable = self.class.openapi_nullable.include?(attr)
next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
end
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end

View File

@ -0,0 +1,52 @@
=begin
#OpenAPI Petstore
#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 7.0.0-SNAPSHOT
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for Petstore::PropertyNameMapping
# Automatically generated by openapi-generator (https://openapi-generator.tech)
# Please update as you see appropriate
describe Petstore::PropertyNameMapping do
let(:instance) { Petstore::PropertyNameMapping.new }
describe 'test an instance of PropertyNameMapping' do
it 'should create an instance of PropertyNameMapping' do
expect(instance).to be_instance_of(Petstore::PropertyNameMapping)
end
end
describe 'test attribute "http_debug_operation"' do
it 'should work' do
# assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/
end
end
describe 'test attribute "underscore_type"' do
it 'should work' do
# assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/
end
end
describe 'test attribute "type"' do
it 'should work' do
# assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/
end
end
describe 'test attribute "type_with_underscore"' do
it 'should work' do
# assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/
end
end
end