Skip to content
Closed
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
32 changes: 32 additions & 0 deletions bin/ruby-client-petstore-faraday.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#!/bin/sh

SCRIPT="$0"
echo "# START SCRIPT: $SCRIPT"

while [ -h "$SCRIPT" ] ; do
ls=`ls -ld "$SCRIPT"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=`dirname "$SCRIPT"`/"$link"
fi
done

if [ ! -d "${APP_DIR}" ]; then
APP_DIR=`dirname "$SCRIPT"`/..
APP_DIR=`cd "${APP_DIR}"; pwd`
fi

executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar"

if [ ! -f "$executable" ]
then
mvn -B clean package
fi

# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/ruby-client -i modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -g ruby -c bin/ruby-petstore-faraday.json -o samples/client/petstore/ruby-faraday $@"

java $JAVA_OPTS -jar $executable $ags
5 changes: 5 additions & 0 deletions bin/ruby-petstore-faraday.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"gemName": "petstore",
"moduleName": "Petstore",
"gemVersion": "1.0.0"
}
1 change: 1 addition & 0 deletions bin/ruby-petstore.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"gemName": "petstore",
"library": "typhoeus",
"moduleName": "Petstore",
"gemVersion": "1.0.0"
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ public class RubyClientCodegen extends AbstractRubyCodegen {
public static final String GEM_DESCRIPTION = "gemDescription";
public static final String GEM_AUTHOR = "gemAuthor";
public static final String GEM_AUTHOR_EMAIL = "gemAuthorEmail";
public static final String FARADAY = "faraday";
public static final String TYPHOEUS = "typhoeus";

protected String gemName;
protected String moduleName;
Expand All @@ -51,8 +53,8 @@ public class RubyClientCodegen extends AbstractRubyCodegen {
protected String libFolder = "lib";
protected String gemLicense = "proprietary";
protected String gemRequiredRubyVersion = ">= 1.9";
protected String gemHomepage = "http://org.openapitools";
protected String gemSummary = "A ruby wrapper for the REST APIs";
protected String gemHomepage = "https://openapitools.org";
protected String gemSummary = "A Ruby SDK for the REST API";
protected String gemDescription = "This gem maps to a REST API";
protected String gemAuthor = "";
protected String gemAuthorEmail = "";
Expand Down Expand Up @@ -90,7 +92,6 @@ public RubyClientCodegen() {
reservedWords.add(word.toLowerCase(Locale.ROOT));
}


// primitives in ruby lang
languageSpecificPrimitives.add("int");
languageSpecificPrimitives.add("array");
Expand Down Expand Up @@ -137,6 +138,18 @@ public RubyClientCodegen() {
cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC).
defaultValue(Boolean.TRUE.toString()));

cliOptions.add(CliOption.newBoolean(FARADAY, "Faraday (https://github.com/lostisland/faraday)"));
cliOptions.add(CliOption.newBoolean(TYPHOEUS, "Typhoeus (https://github.com/typhoeus/typhoeus)"));

supportedLibraries.put(FARADAY, "Faraday (https://github.com/lostisland/faraday)");
supportedLibraries.put(TYPHOEUS, "Typhoeus >= 1.0.1 (https://github.com/typhoeus/typhoeus)");

CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "HTTP library template (sub-template) to use");
libraryOption.setEnum(supportedLibraries);
// set FARADAY as the default
libraryOption.setDefault(FARADAY);
cliOptions.add(libraryOption);
setLibrary(FARADAY);
}

@Override
Expand Down Expand Up @@ -205,10 +218,8 @@ public void processOpts() {
setModelPackage("models");
setApiPackage("api");

supportingFiles.add(new SupportingFile("gemspec.mustache", "", gemName + ".gemspec"));
supportingFiles.add(new SupportingFile("gem.mustache", libFolder, gemName + ".rb"));
String gemFolder = libFolder + File.separator + gemName;
supportingFiles.add(new SupportingFile("api_client.mustache", gemFolder, "api_client.rb"));
supportingFiles.add(new SupportingFile("api_error.mustache", gemFolder, "api_error.rb"));
supportingFiles.add(new SupportingFile("configuration.mustache", gemFolder, "configuration.rb"));
supportingFiles.add(new SupportingFile("version.mustache", gemFolder, "version.rb"));
Expand All @@ -217,9 +228,19 @@ 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("Gemfile.lock.mustache", "", "Gemfile.lock"));
supportingFiles.add(new SupportingFile("rubocop.mustache", "", ".rubocop.yml"));

if (TYPHOEUS.equals(getLibrary())) {
supportingFiles.add(new SupportingFile("api_client.mustache", gemFolder, "api_client.rb"));
supportingFiles.add(new SupportingFile("gemspec.mustache", "", gemName + ".gemspec"));
supportingFiles.add(new SupportingFile("Gemfile.lock.mustache", "", "Gemfile.lock"));
} else if (FARADAY.equals(getLibrary())) {
supportingFiles.add(new SupportingFile("faraday_api_client.mustache", gemFolder, "api_client.rb"));
supportingFiles.add(new SupportingFile("faraday_gemspec.mustache", "", gemName + ".gemspec"));
} else {
throw new RuntimeException("Invalid HTTP library " + getLibrary() + ". Only faraday, typhoeus are supported.");
}

// test files should not be overwritten
writeOptional(outputFolder, new SupportingFile("rspec.mustache", "", ".rspec"));
writeOptional(outputFolder, new SupportingFile("spec_helper.mustache", specFolder, "spec_helper.rb"));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
=begin
{{> api_info}}
=end

require 'date'
require 'json'
require 'logger'
require 'faraday'

module {{moduleName}}
class ApiClient
def self.default
@@default ||= ApiClient.new
end

def initialize(config = Configuration.default)
@config = config
end

attr_reader :config

def call_api(http_method, path, opts = {})
normalized_path = ::File.join(config.base_path, path)

@last_response = connection.public_send(http_method.to_sym.downcase) do |req|
req.url(normalized_path)

req.headers = default_headers.merge(opts[:header_params] || {})
req.body = opts[:body]

query_params = opts[:query_params] || {}
form_params = opts[:form_params] || {}
req.params = query_params.merge(form_params)
end

if @config.debugging
@config.logger.debug "HTTP response body ~BEGIN~\n#{@last_response.body}\n~END~\n"
end

if opts[:return_type]
data = deserialize(@last_response, opts[:return_type])
else
data = nil
end

return data, @last_response.status, @last_response.headers
end

attr_reader :last_response

# Convert object (array, hash, object, etc) to JSON string.
# @param [Object] model object to be converted into JSON string
# @return [String] JSON string representation of the object
def object_to_http_body(model)
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) }
else
local_body = object_to_hash(model)
end
local_body.to_json
end

# Convert object(non-array) to hash.
# @param [Object] obj object to be converted into JSON string
# @return [String] JSON string representation of the object
def object_to_hash(obj)
if obj.respond_to?(:to_hash)
obj.to_hash
else
obj
end
end

# Return Accept header based on an array of accepts provided.
# @param [Array] accepts array for Accept
# @return [String] the Accept header (e.g. application/json)
def select_header_accept(accepts)
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) }
json_accept || accepts.join(',')
end

# Return Content-Type header based on an array of content types provided.
# @param [Array] content_types array for Content-Type
# @return [String] the Content-Type header (e.g. application/json)
def select_header_content_type(content_types)
# use application/json by default
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) }
json_content_type || content_types.first
end

def json_mime?(mime)
(mime == '*/*') || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil?
end

private

def connection
@connection ||= bulid_connection
end

def bulid_connection
Faraday.new(:url => config.base_url) do |builder|
builder.adapter(Faraday.default_adapter)
end
end

def user_agent
@user_agent ||= "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/#{VERSION}/ruby{{/httpUserAgent}}"
end

def default_headers
{
'Content-Type' => 'application/json',
'User-Agent' => user_agent
}
end

# Deserialize the response to the given return type.
#
# @param [Response] response HTTP response
# @param [String] return_type some examples: "User", "Array<User>", "Hash<String, Integer>"
def deserialize(response, return_type)
body = response.body

return nil if body.nil? || body.empty?

# return response body directly for String return type
return body if return_type == 'String'

# ensuring a default content type
content_type = response.headers['Content-Type'] || 'application/json'

fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)

begin
data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
rescue JSON::ParserError => e
if %w(String Date DateTime).include?(return_type)
data = body
else
raise e
end
end

convert_to_type data, return_type
end

# Convert data to the given return type.
# @param [Object] data Data to be converted
# @param [String] return_type Return type
# @return [Mixed] Data in a particular type
def convert_to_type(data, return_type)
return nil if data.nil?
case return_type
when 'String'
data.to_s
when 'Integer'
data.to_i
when 'Float'
data.to_f
when 'BOOLEAN'
data == true
when 'DateTime'
# parse date time (expecting ISO 8601 format)
DateTime.parse data
when 'Date'
# parse date time (expecting ISO 8601 format)
Date.parse data
when 'Object'
# generic object (usually a Hash), return directly
data
when /\AArray<(.+)>\z/
# e.g. Array<Pet>
sub_type = $1
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) }
end
else
# models, e.g. Pet
{{moduleName}}.const_get(return_type).new.tap do |model|
model.build_from_hash data
end
end
end
end
end
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# -*- encoding: utf-8 -*-

=begin
{{> api_info}}
=end

$:.push File.expand_path("../lib", __FILE__)
require "{{gemName}}/version"

Gem::Specification.new do |s|
s.name = "{{gemName}}{{^gemName}}{{{appName}}}{{/gemName}}"
s.version = {{moduleName}}::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["{{gemAuthor}}{{^gemAuthor}}OpenAPI-Generator{{/gemAuthor}}"]
s.email = ["{{gemAuthorEmail}}{{^gemAuthorEmail}}{{infoEmail}}{{/gemAuthorEmail}}"]
s.homepage = "{{gemHomepage}}{{^gemHomepage}}https://openapi-generator.tech{{/gemHomepage}}"
s.summary = "{{gemSummary}}{{^gemSummary}}{{{appName}}} Ruby Gem{{/gemSummary}}"
s.description = "{{gemDescription}}{{^gemDescription}}{{{appDescription}}}{{^appDescription}}{{{appName}}} Ruby Gem{{/appDescription}}{{/gemDescription}}"
{{#gemLicense}}
s.license = '{{{gemLicense}}}'
{{/gemLicense}}
{{^gemLicense}}
s.license = "Unlicense"
{{/gemLicense}}
s.required_ruby_version = "{{{gemRequiredRubyVersion}}}{{^gemRequiredRubyVersion}}>= 1.9{{/gemRequiredRubyVersion}}"

s.add_runtime_dependency 'faraday', '>= 0.14.0'
s.add_runtime_dependency 'json', '~> 2.1', '>= 2.1.0'

s.add_development_dependency 'rspec', '~> 3.6', '>= 3.6.0'
s.add_development_dependency 'vcr', '~> 3.0', '>= 3.0.1'
s.add_development_dependency 'webmock', '~> 1.24', '>= 1.24.3'

s.files = `find *`.split("\n").uniq.sort.select { |f| !f.empty? }
s.test_files = `find spec/*`.split("\n")
s.executables = []
s.require_paths = ["lib"]
end
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ public class RubyClientOptionsProvider implements OptionsProvider {
public static final String GEM_AUTHOR_EMAIL_VALUE = "foo";
public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false";
public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true";
public static final String LIBRARY = "faraday";

@Override
public String getLanguage() {
Expand All @@ -63,6 +64,9 @@ public Map<String, String> createOptions() {
.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true")
.put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE)
.put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE)
.put(CodegenConstants.LIBRARY, LIBRARY)
.put(RubyClientCodegen.FARADAY, "false")
.put(RubyClientCodegen.TYPHOEUS, "false")
.build();
}

Expand Down
Loading