From 58cfacc4cfb726e2af5c956e3286e9f5fcc573aa Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 26 Sep 2012 13:02:27 -0700 Subject: [PATCH] added ruby sample --- bin/ruby-petstore.sh | 19 ++ samples/client/petstore/ruby/Gemfile | 4 + samples/client/petstore/ruby/Gemfile.lock | 53 ++++ samples/client/petstore/ruby/Rakefile | 7 + .../petstore/ruby/RubyPetstoreCodegen.scala | 13 + samples/client/petstore/ruby/lib/Pet_api.rb | 173 +++++++++++ samples/client/petstore/ruby/lib/Store_api.rb | 106 +++++++ samples/client/petstore/ruby/lib/User_api.rb | 289 ++++++++++++++++++ samples/client/petstore/ruby/lib/monkey.rb | 90 ++++++ samples/client/petstore/ruby/lib/swagger.rb | 84 +++++ .../ruby/lib/swagger/configuration.rb | 19 ++ .../petstore/ruby/lib/swagger/request.rb | 186 +++++++++++ .../petstore/ruby/lib/swagger/response.rb | 70 +++++ .../petstore/ruby/lib/swagger/version.rb | 5 + .../client/petstore/ruby/models/Category.rb | 55 ++++ samples/client/petstore/ruby/models/Order.rb | 97 ++++++ samples/client/petstore/ruby/models/Pet.rb | 111 +++++++ samples/client/petstore/ruby/models/Tag.rb | 55 ++++ samples/client/petstore/ruby/models/User.rb | 139 +++++++++ .../client/petstore/ruby/spec/monkey_spec.rb | 33 ++ samples/client/petstore/ruby/spec/pet_spec.rb | 69 +++++ .../client/petstore/ruby/spec/request_spec.rb | 196 ++++++++++++ .../petstore/ruby/spec/response_spec.rb | 59 ++++ samples/client/petstore/ruby/spec/spec.opts | 4 + .../client/petstore/ruby/spec/spec_helper.rb | 51 ++++ .../client/petstore/ruby/spec/swagger_spec.rb | 56 ++++ samples/client/petstore/ruby/swagger.gemspec | 33 ++ src/main/resources/ruby/api.mustache | 87 ++++++ src/main/resources/ruby/model.mustache | 50 +++ src/main/resources/ruby/monkey.mustache | 90 ++++++ src/main/resources/ruby/swagger.mustache | 84 +++++ .../ruby/swagger/configuration.mustache | 19 ++ .../resources/ruby/swagger/request.mustache | 186 +++++++++++ .../resources/ruby/swagger/response.mustache | 70 +++++ .../resources/ruby/swagger/version.mustache | 4 + 35 files changed, 2666 insertions(+) create mode 100755 bin/ruby-petstore.sh create mode 100644 samples/client/petstore/ruby/Gemfile create mode 100644 samples/client/petstore/ruby/Gemfile.lock create mode 100644 samples/client/petstore/ruby/Rakefile create mode 100644 samples/client/petstore/ruby/RubyPetstoreCodegen.scala create mode 100644 samples/client/petstore/ruby/lib/Pet_api.rb create mode 100644 samples/client/petstore/ruby/lib/Store_api.rb create mode 100644 samples/client/petstore/ruby/lib/User_api.rb create mode 100644 samples/client/petstore/ruby/lib/monkey.rb create mode 100644 samples/client/petstore/ruby/lib/swagger.rb create mode 100644 samples/client/petstore/ruby/lib/swagger/configuration.rb create mode 100644 samples/client/petstore/ruby/lib/swagger/request.rb create mode 100644 samples/client/petstore/ruby/lib/swagger/response.rb create mode 100644 samples/client/petstore/ruby/lib/swagger/version.rb create mode 100644 samples/client/petstore/ruby/models/Category.rb create mode 100644 samples/client/petstore/ruby/models/Order.rb create mode 100644 samples/client/petstore/ruby/models/Pet.rb create mode 100644 samples/client/petstore/ruby/models/Tag.rb create mode 100644 samples/client/petstore/ruby/models/User.rb create mode 100644 samples/client/petstore/ruby/spec/monkey_spec.rb create mode 100644 samples/client/petstore/ruby/spec/pet_spec.rb create mode 100644 samples/client/petstore/ruby/spec/request_spec.rb create mode 100644 samples/client/petstore/ruby/spec/response_spec.rb create mode 100644 samples/client/petstore/ruby/spec/spec.opts create mode 100644 samples/client/petstore/ruby/spec/spec_helper.rb create mode 100644 samples/client/petstore/ruby/spec/swagger_spec.rb create mode 100644 samples/client/petstore/ruby/swagger.gemspec create mode 100644 src/main/resources/ruby/api.mustache create mode 100644 src/main/resources/ruby/model.mustache create mode 100644 src/main/resources/ruby/monkey.mustache create mode 100644 src/main/resources/ruby/swagger.mustache create mode 100644 src/main/resources/ruby/swagger/configuration.mustache create mode 100644 src/main/resources/ruby/swagger/request.mustache create mode 100644 src/main/resources/ruby/swagger/response.mustache create mode 100644 src/main/resources/ruby/swagger/version.mustache diff --git a/bin/ruby-petstore.sh b/bin/ruby-petstore.sh new file mode 100755 index 0000000000..6eb6c90cea --- /dev/null +++ b/bin/ruby-petstore.sh @@ -0,0 +1,19 @@ +#!/bin/bash + +echo "" > classpath.txt +for file in `ls target/lib`; + do echo -n 'target/lib/' >> classpath.txt; + echo -n $file >> classpath.txt; + echo -n ':' >> classpath.txt; +done + +for file in `ls target/*.jar`; + do echo -n '' >> classpath.txt; + echo -n $file >> classpath.txt; + echo -n ':' >> classpath.txt; +done +export CLASSPATH=$(cat classpath.txt) + + +export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties" +scala $WORDNIK_OPTS $JAVA_CONFIG_OPTIONS -cp $CLASSPATH "$@" samples/client/petstore/ruby/RubyPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/resources.json special-key diff --git a/samples/client/petstore/ruby/Gemfile b/samples/client/petstore/ruby/Gemfile new file mode 100644 index 0000000000..06d4a65272 --- /dev/null +++ b/samples/client/petstore/ruby/Gemfile @@ -0,0 +1,4 @@ +source "http://rubygems.org" + +# Specify dependencies in swagger.gemspec +gemspec diff --git a/samples/client/petstore/ruby/Gemfile.lock b/samples/client/petstore/ruby/Gemfile.lock new file mode 100644 index 0000000000..f90e3382ed --- /dev/null +++ b/samples/client/petstore/ruby/Gemfile.lock @@ -0,0 +1,53 @@ +PATH + remote: . + specs: + swagger (4.06.08) + addressable (>= 2.2.4) + json (>= 1.4.6) + typhoeus (>= 0.2.1) + +GEM + remote: http://rubygems.org/ + specs: + ZenTest (4.7.0) + addressable (2.2.8) + autotest (4.4.6) + ZenTest (>= 4.4.1) + autotest-fsevent (0.2.8) + sys-uname + autotest-growl (0.2.16) + autotest-rails-pure (4.1.2) + crack (0.3.1) + diff-lcs (1.1.3) + ffi (1.0.11) + json (1.7.0) + mime-types (1.18) + rspec (2.9.0) + rspec-core (~> 2.9.0) + rspec-expectations (~> 2.9.0) + rspec-mocks (~> 2.9.0) + rspec-core (2.9.0) + rspec-expectations (2.9.1) + diff-lcs (~> 1.1.3) + rspec-mocks (2.9.0) + sys-uname (0.9.0) + ffi (>= 1.0.0) + typhoeus (0.3.3) + mime-types + vcr (2.1.1) + webmock (1.8.6) + addressable (>= 2.2.7) + crack (>= 0.1.7) + +PLATFORMS + ruby + +DEPENDENCIES + autotest + autotest-fsevent + autotest-growl + autotest-rails-pure + rspec (>= 2.5.0) + swagger! + vcr (>= 1.5.1) + webmock (>= 1.6.2) diff --git a/samples/client/petstore/ruby/Rakefile b/samples/client/petstore/ruby/Rakefile new file mode 100644 index 0000000000..e62140b167 --- /dev/null +++ b/samples/client/petstore/ruby/Rakefile @@ -0,0 +1,7 @@ +require 'bundler' +Bundler::GemHelper.install_tasks + +require 'rspec/core/rake_task' +require 'swagger' + +RSpec::Core::RakeTask.new('spec') \ No newline at end of file diff --git a/samples/client/petstore/ruby/RubyPetstoreCodegen.scala b/samples/client/petstore/ruby/RubyPetstoreCodegen.scala new file mode 100644 index 0000000000..811ec24f40 --- /dev/null +++ b/samples/client/petstore/ruby/RubyPetstoreCodegen.scala @@ -0,0 +1,13 @@ +import com.wordnik.swagger.codegen.BasicRubyGenerator + +import com.wordnik.swagger.core._ + +object RubyPetstoreCodegen extends BasicRubyGenerator { + def main(args: Array[String]) = generateClient(args) + + // where to write generated code + override def destinationDir = "samples/client/petstore/ruby" + + // package for models + override def modelPackage = Some("models") +} \ No newline at end of file diff --git a/samples/client/petstore/ruby/lib/Pet_api.rb b/samples/client/petstore/ruby/lib/Pet_api.rb new file mode 100644 index 0000000000..0e8bf2d20c --- /dev/null +++ b/samples/client/petstore/ruby/lib/Pet_api.rb @@ -0,0 +1,173 @@ +require "uri" + +class Pet_api + basePath = "http://petstore.swagger.wordnik.com/api" + # apiInvoker = APIInvoker + + def self.escapeString(string) + URI.encode(string.to_s) + end + + def self.get_pet_by_id (pet_id,opts={}) + query_param_keys = [ + ] + + # verify existence of params + raise "pet_id is required" if pet_id.nil? + # set default values and merge with input + options = { + :pet_id => pet_id}.merge(opts) + + #resource path + path = "/pet.{format}/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', escapeString(pet_id)) + + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + headers = nil + post_body = nil + response = Swagger::Request.new(:GET, path, {:params=>queryopts,:headers=>headers, :body=>post_body }).make.body + Pet.new(response) + end + + def self.add_pet (body,opts={}) + query_param_keys = [ + ] + + # verify existence of params + raise "body is required" if body.nil? + # set default values and merge with input + options = { + :body => body}.merge(opts) + + #resource path + path = "/pet.{format}".sub('{format}','json') + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + headers = nil + post_body = nil + if body != nil + if body.is_a?(Array) + array = Array.new + body.each do |item| + if item.respond_to?("to_body".to_sym) + array.push item.to_body + else + array.push item + end + end + post_body = array + + else + if body.respond_to?("to_body".to_sym) + post_body = body.to_body + else + post_body = body + end + end + end + Swagger::Request.new(:POST, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make + + end + + def self.update_pet (body,opts={}) + query_param_keys = [ + ] + + # verify existence of params + raise "body is required" if body.nil? + # set default values and merge with input + options = { + :body => body}.merge(opts) + + #resource path + path = "/pet.{format}".sub('{format}','json') + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + headers = nil + post_body = nil + if body != nil + if body.is_a?(Array) + array = Array.new + body.each do |item| + if item.respond_to?("to_body".to_sym) + array.push item.to_body + else + array.push item + end + end + post_body = array + + else + if body.respond_to?("to_body".to_sym) + post_body = body.to_body + else + post_body = body + end + end + end + Swagger::Request.new(:PUT, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make + + end + + def self.find_pets_by_status (status= "available",opts={}) + query_param_keys = [ + :status] + + # verify existence of params + raise "status is required" if status.nil? + # set default values and merge with input + options = { + :status => status}.merge(opts) + + #resource path + path = "/pet.{format}/findByStatus".sub('{format}','json') + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + headers = nil + post_body = nil + response = Swagger::Request.new(:GET, path, {:params=>queryopts,:headers=>headers, :body=>post_body }).make.body + response.map {|response|Pet.new(response)} + end + + def self.find_pets_by_tags (tags,opts={}) + query_param_keys = [ + :tags] + + # verify existence of params + raise "tags is required" if tags.nil? + # set default values and merge with input + options = { + :tags => tags}.merge(opts) + + #resource path + path = "/pet.{format}/findByTags".sub('{format}','json') + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + headers = nil + post_body = nil + response = Swagger::Request.new(:GET, path, {:params=>queryopts,:headers=>headers, :body=>post_body }).make.body + response.map {|response|Pet.new(response)} + end + + end + diff --git a/samples/client/petstore/ruby/lib/Store_api.rb b/samples/client/petstore/ruby/lib/Store_api.rb new file mode 100644 index 0000000000..bd0fe15253 --- /dev/null +++ b/samples/client/petstore/ruby/lib/Store_api.rb @@ -0,0 +1,106 @@ +require "uri" + +class Store_api + basePath = "http://petstore.swagger.wordnik.com/api" + # apiInvoker = APIInvoker + + def self.escapeString(string) + URI.encode(string.to_s) + end + + def self.get_order_by_id (order_id,opts={}) + query_param_keys = [ + ] + + # verify existence of params + raise "order_id is required" if order_id.nil? + # set default values and merge with input + options = { + :order_id => order_id}.merge(opts) + + #resource path + path = "/store.{format}/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', escapeString(order_id)) + + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + headers = nil + post_body = nil + response = Swagger::Request.new(:GET, path, {:params=>queryopts,:headers=>headers, :body=>post_body }).make.body + Order.new(response) + end + + def self.delete_order (order_id,opts={}) + query_param_keys = [ + ] + + # verify existence of params + raise "order_id is required" if order_id.nil? + # set default values and merge with input + options = { + :order_id => order_id}.merge(opts) + + #resource path + path = "/store.{format}/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', escapeString(order_id)) + + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + headers = nil + post_body = nil + Swagger::Request.new(:DELETE, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make + + end + + def self.place_order (body,opts={}) + query_param_keys = [ + ] + + # verify existence of params + raise "body is required" if body.nil? + # set default values and merge with input + options = { + :body => body}.merge(opts) + + #resource path + path = "/store.{format}/order".sub('{format}','json') + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + headers = nil + post_body = nil + if body != nil + if body.is_a?(Array) + array = Array.new + body.each do |item| + if item.respond_to?("to_body".to_sym) + array.push item.to_body + else + array.push item + end + end + post_body = array + + else + if body.respond_to?("to_body".to_sym) + post_body = body.to_body + else + post_body = body + end + end + end + Swagger::Request.new(:POST, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make + + end + + end + diff --git a/samples/client/petstore/ruby/lib/User_api.rb b/samples/client/petstore/ruby/lib/User_api.rb new file mode 100644 index 0000000000..edc76dd2e6 --- /dev/null +++ b/samples/client/petstore/ruby/lib/User_api.rb @@ -0,0 +1,289 @@ +require "uri" + +class User_api + basePath = "http://petstore.swagger.wordnik.com/api" + # apiInvoker = APIInvoker + + def self.escapeString(string) + URI.encode(string.to_s) + end + + def self.create_users_with_array_input (body,opts={}) + query_param_keys = [ + ] + + # verify existence of params + raise "body is required" if body.nil? + # set default values and merge with input + options = { + :body => body}.merge(opts) + + #resource path + path = "/user.{format}/createWithArray".sub('{format}','json') + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + headers = nil + post_body = nil + if body != nil + if body.is_a?(Array) + array = Array.new + body.each do |item| + if item.respond_to?("to_body".to_sym) + array.push item.to_body + else + array.push item + end + end + post_body = array + + else + if body.respond_to?("to_body".to_sym) + post_body = body.to_body + else + post_body = body + end + end + end + Swagger::Request.new(:POST, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make + + end + + def self.create_user (body,opts={}) + query_param_keys = [ + ] + + # verify existence of params + raise "body is required" if body.nil? + # set default values and merge with input + options = { + :body => body}.merge(opts) + + #resource path + path = "/user.{format}".sub('{format}','json') + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + headers = nil + post_body = nil + if body != nil + if body.is_a?(Array) + array = Array.new + body.each do |item| + if item.respond_to?("to_body".to_sym) + array.push item.to_body + else + array.push item + end + end + post_body = array + + else + if body.respond_to?("to_body".to_sym) + post_body = body.to_body + else + post_body = body + end + end + end + Swagger::Request.new(:POST, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make + + end + + def self.create_users_with_list_input (body,opts={}) + query_param_keys = [ + ] + + # verify existence of params + raise "body is required" if body.nil? + # set default values and merge with input + options = { + :body => body}.merge(opts) + + #resource path + path = "/user.{format}/createWithList".sub('{format}','json') + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + headers = nil + post_body = nil + if body != nil + if body.is_a?(Array) + array = Array.new + body.each do |item| + if item.respond_to?("to_body".to_sym) + array.push item.to_body + else + array.push item + end + end + post_body = array + + else + if body.respond_to?("to_body".to_sym) + post_body = body.to_body + else + post_body = body + end + end + end + Swagger::Request.new(:POST, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make + + end + + def self.update_user (username,body,opts={}) + query_param_keys = [ + ] + + # verify existence of params + raise "username is required" if username.nil? + raise "body is required" if body.nil? + # set default values and merge with input + options = { + :username => username, + :body => body}.merge(opts) + + #resource path + path = "/user.{format}/{username}".sub('{format}','json').sub('{' + 'username' + '}', escapeString(username)) + + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + headers = nil + post_body = nil + if body != nil + if body.is_a?(Array) + array = Array.new + body.each do |item| + if item.respond_to?("to_body".to_sym) + array.push item.to_body + else + array.push item + end + end + post_body = array + + else + if body.respond_to?("to_body".to_sym) + post_body = body.to_body + else + post_body = body + end + end + end + Swagger::Request.new(:PUT, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make + + end + + def self.delete_user (username,opts={}) + query_param_keys = [ + ] + + # verify existence of params + raise "username is required" if username.nil? + # set default values and merge with input + options = { + :username => username}.merge(opts) + + #resource path + path = "/user.{format}/{username}".sub('{format}','json').sub('{' + 'username' + '}', escapeString(username)) + + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + headers = nil + post_body = nil + Swagger::Request.new(:DELETE, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make + + end + + def self.get_user_by_name (username,opts={}) + query_param_keys = [ + ] + + # verify existence of params + raise "username is required" if username.nil? + # set default values and merge with input + options = { + :username => username}.merge(opts) + + #resource path + path = "/user.{format}/{username}".sub('{format}','json').sub('{' + 'username' + '}', escapeString(username)) + + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + headers = nil + post_body = nil + response = Swagger::Request.new(:GET, path, {:params=>queryopts,:headers=>headers, :body=>post_body }).make.body + User.new(response) + end + + def self.login_user (username,password,opts={}) + query_param_keys = [ + :username, :password] + + # verify existence of params + raise "username is required" if username.nil? + raise "password is required" if password.nil? + # set default values and merge with input + options = { + :username => username, + :password => password}.merge(opts) + + #resource path + path = "/user.{format}/login".sub('{format}','json') + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + headers = nil + post_body = nil + response = Swagger::Request.new(:GET, path, {:params=>queryopts,:headers=>headers, :body=>post_body }).make.body + string.new(response) + end + + def self.logout_user (opts={}) + query_param_keys = [ + ] + + # set default values and merge with input + options = { + }.merge(opts) + + #resource path + path = "/user.{format}/logout".sub('{format}','json') + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + headers = nil + post_body = nil + Swagger::Request.new(:GET, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make + + end + + end + diff --git a/samples/client/petstore/ruby/lib/monkey.rb b/samples/client/petstore/ruby/lib/monkey.rb new file mode 100644 index 0000000000..54cd22170e --- /dev/null +++ b/samples/client/petstore/ruby/lib/monkey.rb @@ -0,0 +1,90 @@ +# module Swagger + class Object + + unless Object.method_defined? :blank? + def blank? + respond_to?(:empty?) ? empty? : !self + end + end + + unless Object.method_defined? :present? + def present? + !blank? + end + end + + end + + class String + + unless String.method_defined? :underscore + def underscore + self.gsub(/::/, '/'). + gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). + gsub(/([a-z\d])([A-Z])/,'\1_\2'). + tr("-", "_"). + downcase + end + end + + unless String.method_defined? :camelize + def camelize(first_letter_in_uppercase = true) + if first_letter_in_uppercase != :lower + self.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } + else + self.to_s[0].chr.downcase + camelize(self)[1..-1] + end + end + end + + end + + class Hash + + unless Hash.method_defined? :stringify_keys + def stringify_keys + inject({}) do |options, (key, value)| + options[key.to_s] = value + options + end + end + end + + unless Hash.method_defined? :stringify_keys! + def stringify_keys! + self.replace(self.stringify_keys) + end + end + + unless Hash.method_defined? :symbolize_keys + def symbolize_keys + inject({}) do |options, (key, value)| + options[(key.to_sym rescue key) || key] = value + options + end + end + end + + unless Hash.method_defined? :symbolize_keys! + def symbolize_keys! + self.replace(self.symbolize_keys) + end + end + + unless Hash.method_defined? :symbolize_and_underscore_keys + def symbolize_and_underscore_keys + inject({}) do |options, (key, value)| + options[(key.to_s.underscore.to_sym rescue key) || key] = value + options + end + end + end + + unless Hash.method_defined? :symbolize_and_underscore_keys! + def symbolize_and_underscore_keys! + self.replace(self.symbolize_and_underscore_keys) + end + end + + end +# end diff --git a/samples/client/petstore/ruby/lib/swagger.rb b/samples/client/petstore/ruby/lib/swagger.rb new file mode 100644 index 0000000000..de48af3a33 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger.rb @@ -0,0 +1,84 @@ +require 'monkey' +require 'swagger/configuration' +require 'swagger/request' +require 'swagger/response' +require 'swagger/version' +require 'logger' + +module Swagger + + class << self + attr_accessor :logger + + # 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 + + # 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 + self.configuration ||= Configuration.new + yield(configuration) if block_given? + + # Configure logger. Default to use Rails + self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT)) + + # remove :// from scheme + configuration.scheme.sub!(/:\/\//, '') + + # remove http(s):// and anything after a slash + configuration.host.sub!(/https?:\/\//, '') + configuration.host = configuration.host.split('/').first + + # Add leading and trailing slashes to base_path + configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/') + configuration.base_path = "" if configuration.base_path == "/" + end + + def authenticated? + Swagger.configuration.auth_token.present? + end + + def de_authenticate + Swagger.configuration.auth_token = nil + end + + 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 + +end + +class ServerError < StandardError +end + +class ClientError < StandardError +end diff --git a/samples/client/petstore/ruby/lib/swagger/configuration.rb b/samples/client/petstore/ruby/lib/swagger/configuration.rb new file mode 100644 index 0000000000..137abd1bdf --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger/configuration.rb @@ -0,0 +1,19 @@ +module Swagger + + class Configuration + require 'swagger/version' + + attr_accessor :format, :api_key, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger + + # Defaults go in here.. + def initialize + @format = 'json' + @scheme = 'http' + @host = 'api.wordnik.com' + @base_path = '/v4' + @user_agent = "ruby-#{Swagger::VERSION}" + end + + end + +end diff --git a/samples/client/petstore/ruby/lib/swagger/request.rb b/samples/client/petstore/ruby/lib/swagger/request.rb new file mode 100644 index 0000000000..93a8ddead2 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger/request.rb @@ -0,0 +1,186 @@ +module Swagger + + class Request + require 'uri' + require 'addressable/uri' + require 'typhoeus' + require "swagger/version" + + attr_accessor :host, :path, :format, :params, :body, :http_method, :headers + + + # 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 + } + + # api_key from headers hash trumps the default, even if its value is blank + if attributes[:headers].present? && attributes[:headers].has_key?(:api_key) + 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 + # + def url(options = {}) + u = Addressable::URI.new( + :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 + # + # e.g. /word.{format}/{word}/entries => /word.json/cat/entries + def interpreted_path + p = self.path.dup + + # Fill in the path params + self.params.each_pair do |key, value| + p = p.gsub("{#{key}}", value.to_s) + end + + # 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 + unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } + p = p.sub(/^(\/?\w+)/, "\\1.#{format}") + 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. + # + def outgoing_body + body.is_a?(String) ? body : body.to_json + end + + # Construct a query string from the query-string-type params + def query_string + + # Iterate over all params, + # .. removing the ones that are part of the path itself. + # .. stringifying values so Addressable doesn't blow up. + query_values = {} + self.params.each_pair do |key, value| + next if self.path.include? "{#{key}}" # skip path params + next if value.blank? && value.class != FalseClass # skip empties + key = key.to_s.camelize(:lower).to_sym unless key.to_sym == :api_key # api_key is not a camelCased param + 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 + 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 :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/, '
') # <- This was for RestClient + @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus + end + + end +end diff --git a/samples/client/petstore/ruby/lib/swagger/response.rb b/samples/client/petstore/ruby/lib/swagger/response.rb new file mode 100644 index 0000000000..a42cf99d4d --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger/response.rb @@ -0,0 +1,70 @@ +module Swagger + + class Response + require 'json' + + attr_accessor :raw + + def initialize(raw) + self.raw = raw + + case self.code + when 500..510 then raise(ServerError, self.error_message) + when 299..426 then raise(ClientError, self.error_message) + 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 + 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/, '
') + end + end + + def pretty_headers + JSON.pretty_generate(headers).gsub(/\n/, '
') + end + + end +end diff --git a/samples/client/petstore/ruby/lib/swagger/version.rb b/samples/client/petstore/ruby/lib/swagger/version.rb new file mode 100644 index 0000000000..dfd2ddad20 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger/version.rb @@ -0,0 +1,5 @@ +module Swagger + VERSION = "4.06.08" +end + + diff --git a/samples/client/petstore/ruby/models/Category.rb b/samples/client/petstore/ruby/models/Category.rb new file mode 100644 index 0000000000..df47a88e91 --- /dev/null +++ b/samples/client/petstore/ruby/models/Category.rb @@ -0,0 +1,55 @@ +class Category + attr_accessor :id, :name + + # :internal => :external + def self.attribute_map + { + :id => :id, :name => :name + + } + end + + def initialize(attributes = {}) + # Morph attribute keys into undescored rubyish style + if attributes.to_s != "" + + if Category.attribute_map["id".to_sym] != nil + name = "id".to_sym + value = attributes["id"] + + if value.is_a?(Array) + array = Array.new + value.each do |arrayValue| + array.push arrayValue + end + send("#{name}=", array) if self.respond_to?(name) + else + send("#{name}=", value) if self.respond_to?(name) + end + end + if Category.attribute_map["name".to_sym] != nil + name = "name".to_sym + value = attributes["name"] + + if value.is_a?(Array) + array = Array.new + value.each do |arrayValue| + array.push arrayValue + end + send("#{name}=", array) if self.respond_to?(name) + else + send("#{name}=", value) if self.respond_to?(name) + end + end + end + end + + def to_body + body = {} + Category.attribute_map.each_pair do |key,value| + body[value] = self.send(key) unless self.send(key).nil? + end + body + end +end + diff --git a/samples/client/petstore/ruby/models/Order.rb b/samples/client/petstore/ruby/models/Order.rb new file mode 100644 index 0000000000..e6244d0a13 --- /dev/null +++ b/samples/client/petstore/ruby/models/Order.rb @@ -0,0 +1,97 @@ +class Order + attr_accessor :id, :pet_id, :status, :quantity, :ship_date + + # :internal => :external + def self.attribute_map + { + :id => :id, :pet_id => :petId, :status => :status, :quantity => :quantity, :ship_date => :shipDate + + } + end + + def initialize(attributes = {}) + # Morph attribute keys into undescored rubyish style + if attributes.to_s != "" + + if Order.attribute_map["id".to_sym] != nil + name = "id".to_sym + value = attributes["id"] + + if value.is_a?(Array) + array = Array.new + value.each do |arrayValue| + array.push arrayValue + end + send("#{name}=", array) if self.respond_to?(name) + else + send("#{name}=", value) if self.respond_to?(name) + end + end + if Order.attribute_map["pet_id".to_sym] != nil + name = "pet_id".to_sym + value = attributes["petId"] + + if value.is_a?(Array) + array = Array.new + value.each do |arrayValue| + array.push arrayValue + end + send("#{name}=", array) if self.respond_to?(name) + else + send("#{name}=", value) if self.respond_to?(name) + end + end + if Order.attribute_map["status".to_sym] != nil + name = "status".to_sym + value = attributes["status"] + + if value.is_a?(Array) + array = Array.new + value.each do |arrayValue| + array.push arrayValue + end + send("#{name}=", array) if self.respond_to?(name) + else + send("#{name}=", value) if self.respond_to?(name) + end + end + if Order.attribute_map["quantity".to_sym] != nil + name = "quantity".to_sym + value = attributes["quantity"] + + if value.is_a?(Array) + array = Array.new + value.each do |arrayValue| + array.push arrayValue + end + send("#{name}=", array) if self.respond_to?(name) + else + send("#{name}=", value) if self.respond_to?(name) + end + end + if Order.attribute_map["ship_date".to_sym] != nil + name = "ship_date".to_sym + value = attributes["shipDate"] + + if value.is_a?(Array) + array = Array.new + value.each do |arrayValue| + array.push Date.new(arrayValue) + end + send("#{name}=", array) if self.respond_to?(name) + else + send("#{name}=", value) if self.respond_to?(name) + end + end + end + end + + def to_body + body = {} + Order.attribute_map.each_pair do |key,value| + body[value] = self.send(key) unless self.send(key).nil? + end + body + end +end + diff --git a/samples/client/petstore/ruby/models/Pet.rb b/samples/client/petstore/ruby/models/Pet.rb new file mode 100644 index 0000000000..7aa7da11b7 --- /dev/null +++ b/samples/client/petstore/ruby/models/Pet.rb @@ -0,0 +1,111 @@ +class Pet + attr_accessor :id, :tags, :category, :status, :name, :photo_urls + + # :internal => :external + def self.attribute_map + { + :id => :id, :tags => :tags, :category => :category, :status => :status, :name => :name, :photo_urls => :photoUrls + + } + end + + def initialize(attributes = {}) + # Morph attribute keys into undescored rubyish style + if attributes.to_s != "" + + if Pet.attribute_map["id".to_sym] != nil + name = "id".to_sym + value = attributes["id"] + + if value.is_a?(Array) + array = Array.new + value.each do |arrayValue| + array.push arrayValue + end + send("#{name}=", array) if self.respond_to?(name) + else + send("#{name}=", value) if self.respond_to?(name) + end + end + if Pet.attribute_map["tags".to_sym] != nil + name = "tags".to_sym + value = attributes["tags"] + + if value.is_a?(Array) + array = Array.new + value.each do |arrayValue| + array.push Tag.new(arrayValue) + end + send("#{name}=", array) if self.respond_to?(name) + else + send("#{name}=", value) if self.respond_to?(name) + end + end + if Pet.attribute_map["category".to_sym] != nil + name = "category".to_sym + value = attributes["category"] + + if value.is_a?(Array) + array = Array.new + value.each do |arrayValue| + array.push Category.new(arrayValue) + end + send("#{name}=", array) if self.respond_to?(name) + else + send("#{name}=", value) if self.respond_to?(name) + end + end + if Pet.attribute_map["status".to_sym] != nil + name = "status".to_sym + value = attributes["status"] + + if value.is_a?(Array) + array = Array.new + value.each do |arrayValue| + array.push arrayValue + end + send("#{name}=", array) if self.respond_to?(name) + else + send("#{name}=", value) if self.respond_to?(name) + end + end + if Pet.attribute_map["name".to_sym] != nil + name = "name".to_sym + value = attributes["name"] + + if value.is_a?(Array) + array = Array.new + value.each do |arrayValue| + array.push arrayValue + end + send("#{name}=", array) if self.respond_to?(name) + else + send("#{name}=", value) if self.respond_to?(name) + end + end + if Pet.attribute_map["photo_urls".to_sym] != nil + name = "photo_urls".to_sym + value = attributes["photoUrls"] + + if value.is_a?(Array) + array = Array.new + value.each do |arrayValue| + array.push arrayValue + end + send("#{name}=", array) if self.respond_to?(name) + else + send("#{name}=", value) if self.respond_to?(name) + end + end + end + end + + def to_body + body = {} + Pet.attribute_map.each_pair do |key,value| + body[value] = self.send(key) unless self.send(key).nil? + end + body + end +end + diff --git a/samples/client/petstore/ruby/models/Tag.rb b/samples/client/petstore/ruby/models/Tag.rb new file mode 100644 index 0000000000..0dbc9be216 --- /dev/null +++ b/samples/client/petstore/ruby/models/Tag.rb @@ -0,0 +1,55 @@ +class Tag + attr_accessor :id, :name + + # :internal => :external + def self.attribute_map + { + :id => :id, :name => :name + + } + end + + def initialize(attributes = {}) + # Morph attribute keys into undescored rubyish style + if attributes.to_s != "" + + if Tag.attribute_map["id".to_sym] != nil + name = "id".to_sym + value = attributes["id"] + + if value.is_a?(Array) + array = Array.new + value.each do |arrayValue| + array.push arrayValue + end + send("#{name}=", array) if self.respond_to?(name) + else + send("#{name}=", value) if self.respond_to?(name) + end + end + if Tag.attribute_map["name".to_sym] != nil + name = "name".to_sym + value = attributes["name"] + + if value.is_a?(Array) + array = Array.new + value.each do |arrayValue| + array.push arrayValue + end + send("#{name}=", array) if self.respond_to?(name) + else + send("#{name}=", value) if self.respond_to?(name) + end + end + end + end + + def to_body + body = {} + Tag.attribute_map.each_pair do |key,value| + body[value] = self.send(key) unless self.send(key).nil? + end + body + end +end + diff --git a/samples/client/petstore/ruby/models/User.rb b/samples/client/petstore/ruby/models/User.rb new file mode 100644 index 0000000000..34eb37ffc2 --- /dev/null +++ b/samples/client/petstore/ruby/models/User.rb @@ -0,0 +1,139 @@ +class User + attr_accessor :id, :last_name, :username, :phone, :email, :user_status, :first_name, :password + + # :internal => :external + def self.attribute_map + { + :id => :id, :last_name => :lastName, :username => :username, :phone => :phone, :email => :email, :user_status => :userStatus, :first_name => :firstName, :password => :password + + } + end + + def initialize(attributes = {}) + # Morph attribute keys into undescored rubyish style + if attributes.to_s != "" + + if User.attribute_map["id".to_sym] != nil + name = "id".to_sym + value = attributes["id"] + + if value.is_a?(Array) + array = Array.new + value.each do |arrayValue| + array.push arrayValue + end + send("#{name}=", array) if self.respond_to?(name) + else + send("#{name}=", value) if self.respond_to?(name) + end + end + if User.attribute_map["last_name".to_sym] != nil + name = "last_name".to_sym + value = attributes["lastName"] + + if value.is_a?(Array) + array = Array.new + value.each do |arrayValue| + array.push arrayValue + end + send("#{name}=", array) if self.respond_to?(name) + else + send("#{name}=", value) if self.respond_to?(name) + end + end + if User.attribute_map["username".to_sym] != nil + name = "username".to_sym + value = attributes["username"] + + if value.is_a?(Array) + array = Array.new + value.each do |arrayValue| + array.push arrayValue + end + send("#{name}=", array) if self.respond_to?(name) + else + send("#{name}=", value) if self.respond_to?(name) + end + end + if User.attribute_map["phone".to_sym] != nil + name = "phone".to_sym + value = attributes["phone"] + + if value.is_a?(Array) + array = Array.new + value.each do |arrayValue| + array.push arrayValue + end + send("#{name}=", array) if self.respond_to?(name) + else + send("#{name}=", value) if self.respond_to?(name) + end + end + if User.attribute_map["email".to_sym] != nil + name = "email".to_sym + value = attributes["email"] + + if value.is_a?(Array) + array = Array.new + value.each do |arrayValue| + array.push arrayValue + end + send("#{name}=", array) if self.respond_to?(name) + else + send("#{name}=", value) if self.respond_to?(name) + end + end + if User.attribute_map["user_status".to_sym] != nil + name = "user_status".to_sym + value = attributes["userStatus"] + + if value.is_a?(Array) + array = Array.new + value.each do |arrayValue| + array.push arrayValue + end + send("#{name}=", array) if self.respond_to?(name) + else + send("#{name}=", value) if self.respond_to?(name) + end + end + if User.attribute_map["first_name".to_sym] != nil + name = "first_name".to_sym + value = attributes["firstName"] + + if value.is_a?(Array) + array = Array.new + value.each do |arrayValue| + array.push arrayValue + end + send("#{name}=", array) if self.respond_to?(name) + else + send("#{name}=", value) if self.respond_to?(name) + end + end + if User.attribute_map["password".to_sym] != nil + name = "password".to_sym + value = attributes["password"] + + if value.is_a?(Array) + array = Array.new + value.each do |arrayValue| + array.push arrayValue + end + send("#{name}=", array) if self.respond_to?(name) + else + send("#{name}=", value) if self.respond_to?(name) + end + end + end + end + + def to_body + body = {} + User.attribute_map.each_pair do |key,value| + body[value] = self.send(key) unless self.send(key).nil? + end + body + end +end + diff --git a/samples/client/petstore/ruby/spec/monkey_spec.rb b/samples/client/petstore/ruby/spec/monkey_spec.rb new file mode 100644 index 0000000000..71c04921f1 --- /dev/null +++ b/samples/client/petstore/ruby/spec/monkey_spec.rb @@ -0,0 +1,33 @@ +require 'spec_helper' + +describe String do + + it "underscores" do + "thisIsATest".underscore.should == "this_is_a_test" + end + + it "camelizes" do + "camel_toe".camelize.should == "CamelToe" + end + + it "camelizes with leading minisculity" do + "dromedary_larry".camelize(:lower).should == "dromedaryLarry" + end + +end + +describe Hash do + + it "symbolizes keys" do + h = {'a' => 1, :b => 2 } + h.symbolize_keys.should be_a Hash + h.symbolize_keys.keys.should == [:a, :b] + end + + it "symbolizes and underscores keys" do + h = {'assHat' => 1, :bargainBasement => 2 } + h.symbolize_and_underscore_keys.should be_a Hash + h.symbolize_and_underscore_keys.keys.should == [:ass_hat, :bargain_basement] + end + +end \ No newline at end of file diff --git a/samples/client/petstore/ruby/spec/pet_spec.rb b/samples/client/petstore/ruby/spec/pet_spec.rb new file mode 100644 index 0000000000..ef71a988bb --- /dev/null +++ b/samples/client/petstore/ruby/spec/pet_spec.rb @@ -0,0 +1,69 @@ +require 'spec_helper' + +describe "Pet" do + before do + Swagger.configure do |config| + config.api_key = 'special-key' + config.host = 'petstore.swagger.wordnik.com' + config.base_path = '/api' + end + end + + describe "pet methods" do + it "should fetch a pet object" do + pet = Pet_api.get_pet_by_id(1) + pet.id.should == 1 + pet.name.should == "Cat 1" + end + + it "should find pets by status" do + pets = Pet_api.find_pets_by_status('available') + pets.length.should >= 3 + end + + it "should not find a pet with invalid status" do + pets = Pet_api.find_pets_by_status('dead') + pets.length.should == 0 + end + + it "should find a pet by status" do + pets = Pet_api.find_pets_by_status("available,sold") + pets.map {|pet| + if(pet.status != 'available' && pet.status != 'sold') + raise "pet status wasn't right" + end + } + end + + it "should update a pet" do + pet = Pet.new({:id => 99, :name => 'programmer', :status => 'coding'}) + Pet_api.add_pet(pet) + + fetched = Pet_api.get_pet_by_id(99) + fetched.id.should == 99 + end + + it "should create a pet" do + pet = Pet.new({:id => 100, :name => "Gorilla"}) + Pet_api.add_pet(pet) + + pet = Pet_api.get_pet_by_id(100) + pet.id.should == 100 + end + end +end + +describe "Store" do + before do + Swagger.configure do |config| + config.api_key = 'special-key' + config.host = 'petstore.swagger.wordnik.com' + config.base_path = '/api' + end + end + + it "should fetch an order" do + item = Store_api.get_order_by_id(1) + item.id.should == 1 + end +end \ No newline at end of file diff --git a/samples/client/petstore/ruby/spec/request_spec.rb b/samples/client/petstore/ruby/spec/request_spec.rb new file mode 100644 index 0000000000..e2afd12687 --- /dev/null +++ b/samples/client/petstore/ruby/spec/request_spec.rb @@ -0,0 +1,196 @@ +require 'spec_helper' + +describe Swagger::Request do + + before(:each) do + @default_http_method = :get + @default_path = "pet/fancy" + @default_params = { + :params => {:foo => "1", :bar => "2"} + } + @request = Swagger::Request.new(@default_http_method, @default_path, @default_params) + end + + describe "initialization" do + it "sets default response format to json" do + @request.format.should == 'json' + end + + it "allows params to be nil" do + @request = Swagger::Request.new(@default_http_method, @default_path, :params => nil) + @request.query_string.should == "" + end + + end + + describe "attr_accessors" do + + it "has working attributes" do + @request.format.to_s.should == 'json' + end + + it "allows attributes to be overwritten" do + @request.http_method.should == :get + @request.http_method = "post" + @request.http_method.should == 'post' + end + + end + + describe "url" do + + it "constructs a query string" do + @request.query_string.should == "?bar=2&foo=1" + end + + it "constructs a full url" do + @request.url.should == "http://petstore.swagger.wordnik.com/api/pet.json/fancy?bar=2&foo=1" + end + + end + + describe "body" do + + it "camelCases parameters" do + @request = Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({ + :body => { + :bad_dog => 'bud', + :goodDog => "dud" + } + })) + @request.body.keys.should == [:badDog, :goodDog] + end + + end + + describe "path" do + + it "accounts for a total absence of format in the path string" do + @request = Swagger::Request.new(:get, "/word/{word}/entries", @default_params.merge({ + :format => "xml", + :params => { + :word => "cat" + } + })) + @request.url.should == "http://petstore.swagger.wordnik.com/api/word.xml/cat/entries" + end + + it "does string substitution on path params" do + @request = Swagger::Request.new(:get, "/word.{format}/{word}/entries", @default_params.merge({ + :format => "xml", + :params => { + :word => "cat" + } + })) + @request.url.should == "http://petstore.swagger.wordnik.com/api/word.xml/cat/entries" + end + + it "leaves path-bound params out of the query string" do + @request = Swagger::Request.new(:get, "/word.{format}/{word}/entries", @default_params.merge({ + :params => { + :word => "cat", + :limit => 20 + } + })) + @request.query_string.should == "?limit=20" + end + + it "returns a question-mark free (blank) query string if no query params are present" do + @request = Swagger::Request.new(:get, "/word.{format}/{word}/entries", @default_params.merge({ + :params => { + :word => "cat", + } + })) + @request.query_string.should == "" + end + + it "removes blank params" do + @request = Swagger::Request.new(:get, "words/fancy", @default_params.merge({ + :params => { + :word => "dog", + :limit => "", + :foo => "criminy" + } + })) + @request.query_string.should == "?foo=criminy&word=dog" + end + + it "URI encodes the path" do + @request = Swagger::Request.new(:get, "word.{format}/{word}/definitions", @default_params.merge({ + :params => { + :word => "bill gates" + } + })) + @request.url.should =~ /word.json\/bill\%20gates\/definitions/ + end + + it "converts numeric params to strings" do + @request = Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({ + :params => { + :limit => 100 + } + })) + + @request.interpreted_path.should_not be_nil + @request.query_string.should =~ /\?limit=100/ + @request.url.should =~ /\?limit=100/ + end + + it "camelCases parameters" do + @request = Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({ + :params => { + :bad_dog => 'bud', + :goodDog => "dud" + } + })) + @request.query_string.should == "?badDog=bud&goodDog=dud" + end + + it "converts boolean values to their string representation" do + params = {:stringy => "fish", :truthy => true, :falsey => false} + @request = Swagger::Request.new(:get, 'fakeMethod', :params => params) + @request.query_string.should == "?falsey=false&stringy=fish&truthy=true" + end + + end + + describe "API key" do + + it "is inferred from the Swagger base configuration by default" do + Swagger.configure {|c| c.api_key = "xyz" } + Swagger::Request.new(:get, "word/json").headers[:api_key].should == "xyz" + end + + it "can be obfuscated for public display" do + @request = Swagger::Request.new(:get, "words/fancy", @default_params.merge({ + :params => { + :word => "dog", + :api_key => "123456" + } + })) + + @request.url.should =~ /api\_key=123456/ + @request.url(:obfuscated => true).should =~ /api\_key=YOUR\_API\_KEY/ + end + + it "allows a key in the params to override the configuration-level key, even if it's blank" do + Swagger.configure {|c| c.api_key = "abc" } + @request_with_key = Swagger::Request.new(:get, "word/json", :params => {:api_key => "jkl"}) + @request_with_key.headers[:api_key].should be_nil + @request_with_key.params[:api_key].should == "jkl" + + @request_without_key = Swagger::Request.new(:get, "word/json", :params => {:api_key => nil}) + @request_without_key.headers[:api_key].should be_nil + @request_without_key.params[:api_key].should be_nil + end + + it "allows a key in the headers to override the configuration-level key, even if it's blank" do + Swagger.configure {|c| c.api_key = "hij" } + Swagger::Request.new(:get, "word/json").headers[:api_key].should == "hij" + Swagger::Request.new(:get, "word/json", :headers => {:api_key => "jkl"}).headers[:api_key].should == "jkl" + Swagger::Request.new(:get, "word/json", :headers => {:api_key => nil}).headers[:api_key].should be_nil + end + + end + +end \ No newline at end of file diff --git a/samples/client/petstore/ruby/spec/response_spec.rb b/samples/client/petstore/ruby/spec/response_spec.rb new file mode 100644 index 0000000000..1092ee9d19 --- /dev/null +++ b/samples/client/petstore/ruby/spec/response_spec.rb @@ -0,0 +1,59 @@ +require 'spec_helper' + +describe Swagger::Response do + + before(:each) do + + VCR.use_cassette('pet_resource', :record => :new_episodes) do + @raw = Typhoeus::Request.get("http://petstore.swagger.wordnik.com/api/pet.json") + end + + @response = Swagger::Response.new(@raw) + end + + describe "initialization" do + it "sets body" do + @response.body.class.should == Hash + @response.body.has_key?('apis').should == true + end + + it "sets code" do + @response.code.should == 200 + end + + it "converts header string into a hash" do + @response.headers.class.should == Hash + end + end + + describe "format" do + + it "recognizes json" do + @response.format.should == 'json' + @response.json?.should == true + end + + it "recognizes xml" do + VCR.use_cassette('xml_response_request', :record => :new_episodes) do + @raw = Typhoeus::Request.get("http://petstore.swagger.wordnik.com/api/pet.xml") + end + @response = Swagger::Response.new(@raw) + @response.format.should == 'xml' + @response.xml?.should == true + end + + end + + describe "prettiness" do + + it "has a pretty json body" do + @response.pretty_body.should =~ /\{.*\}/ + end + + it "has pretty headers" do + @response.pretty_headers.should =~ /\{.*\}/ + end + + end + +end \ No newline at end of file diff --git a/samples/client/petstore/ruby/spec/spec.opts b/samples/client/petstore/ruby/spec/spec.opts new file mode 100644 index 0000000000..391705bf8b --- /dev/null +++ b/samples/client/petstore/ruby/spec/spec.opts @@ -0,0 +1,4 @@ +--colour +--format progress +--loadby mtime +--reverse diff --git a/samples/client/petstore/ruby/spec/spec_helper.rb b/samples/client/petstore/ruby/spec/spec_helper.rb new file mode 100644 index 0000000000..926f8e2abd --- /dev/null +++ b/samples/client/petstore/ruby/spec/spec_helper.rb @@ -0,0 +1,51 @@ +require 'rubygems' +require 'bundler/setup' +require 'monkey' +require 'swagger' +require 'vcr' +require 'typhoeus' +require 'json' +require 'yaml' +require 'rspec' + +Dir[File.join(File.dirname(__FILE__), "../lib/*.rb")].each {|file| require file } +Dir[File.join(File.dirname(__FILE__), "../models/*.rb")].each {|file| require file } +Dir[File.join(File.dirname(__FILE__), "../resources/*.rb")].each {|file| require file } + +RSpec.configure do |config| + # some (optional) config here +end + +WebMock.allow_net_connect! if defined? WebMock + +def help + puts "\nOh noes! You gotta stuff your swagger credentials in ~/.swagger.yml like so:\n\n" + puts "api_key: '12345abcdefg'" + puts "username: 'fumanchu'" + puts "password: 'kalamazoo'\n\n" + exit +end + +# Parse ~/.swagger.yml for user credentials +begin + CREDENTIALS = YAML::load_file(File.join(ENV['HOME'], ".swagger.yml")).symbolize_keys +rescue + help +end + +def configure_swagger + Swagger.configure do |config| + config.api_key = "special-key" + config.username = "" + config.password = "" + + config.host = 'petstore.swagger.wordnik.com' + config.base_path = '/api' + end +end + +configure_swagger + +# A random string to tack onto stuff to ensure we're not seeing +# data from a previous test run +RAND = ("a".."z").to_a.sample(8).join diff --git a/samples/client/petstore/ruby/spec/swagger_spec.rb b/samples/client/petstore/ruby/spec/swagger_spec.rb new file mode 100644 index 0000000000..4aedc85382 --- /dev/null +++ b/samples/client/petstore/ruby/spec/swagger_spec.rb @@ -0,0 +1,56 @@ +# require 'spec_helper' +require File.dirname(__FILE__) + '/spec_helper' + +describe Swagger do + + before(:each) do + configure_swagger + end + + after(:each) do + end + + context 'initialization' do + + context 'URL stuff' do + + context 'host' do + it 'removes http from host' do + Swagger.configure {|c| c.host = 'http://example.com' } + Swagger.configuration.host.should == 'example.com' + end + + it 'removes https from host' do + Swagger.configure {|c| c.host = 'https://wookiee.com' } + Swagger.configuration.host.should == 'wookiee.com' + end + + it 'removes trailing path from host' do + Swagger.configure {|c| c.host = 'hobo.com/v4' } + Swagger.configuration.host.should == 'hobo.com' + end + end + + context 'base_path' do + it "prepends a slash to base_path" do + Swagger.configure {|c| c.base_path = 'v4/dog' } + Swagger.configuration.base_path.should == '/v4/dog' + end + + it "doesn't prepend a slash if one is already there" do + Swagger.configure {|c| c.base_path = '/v4/dog' } + Swagger.configuration.base_path.should == '/v4/dog' + end + + it "ends up as a blank string if nil" do + Swagger.configure {|c| c.base_path = nil } + Swagger.configuration.base_path.should == '' + end + + end + + end + + end + +end \ No newline at end of file diff --git a/samples/client/petstore/ruby/swagger.gemspec b/samples/client/petstore/ruby/swagger.gemspec new file mode 100644 index 0000000000..61bab334b3 --- /dev/null +++ b/samples/client/petstore/ruby/swagger.gemspec @@ -0,0 +1,33 @@ +# -*- encoding: utf-8 -*- +$:.push File.expand_path("../lib", __FILE__) +require "swagger/version" + +Gem::Specification.new do |s| + s.name = "swagger" + s.version = Swagger::VERSION + s.platform = Gem::Platform::RUBY + s.authors = ["Zeke Sikelianos", "Tony Tam"] + s.email = ["zeke@wordnik.com", "tony@wordnik.com"] + s.homepage = "http://developer.wordnik.com" + s.summary = %q{A ruby wrapper for the swagger APIs} + s.description = %q{This gem maps to a swagger API} + + s.rubyforge_project = "swagger" + + s.add_dependency 'typhoeus', '>=0.2.1' + s.add_dependency 'addressable', '>=2.2.4' + s.add_dependency 'json', '>=1.4.6' + + s.add_development_dependency 'rspec', '>=2.5.0' + s.add_development_dependency 'vcr', '>=1.5.1' + s.add_development_dependency 'webmock', '>=1.6.2' + s.add_development_dependency 'autotest' + s.add_development_dependency 'autotest-rails-pure' + s.add_development_dependency 'autotest-growl' + s.add_development_dependency 'autotest-fsevent' + + 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 diff --git a/src/main/resources/ruby/api.mustache b/src/main/resources/ruby/api.mustache new file mode 100644 index 0000000000..445d394611 --- /dev/null +++ b/src/main/resources/ruby/api.mustache @@ -0,0 +1,87 @@ +require "uri" + +{{#operations}} +class {{classname}} + basePath = "{{basePath}}" + # apiInvoker = APIInvoker + + def self.escapeString(string) + URI.encode(string.to_s) + end + + {{#operation}} + def self.{{nickname}} ({{#allParams}}{{paramName}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}},{{/allParams}} opts={}) + query_param_keys = [ + {{#queryParams}}:{{paramName}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}{{newline}}{{/hasMore}} + {{/queryParams}} + ] + + {{#requiredParamCount}} + + # verify existence of params + {{#requiredParams}} + raise "{{{paramName}}} is required" if {{{paramName}}}.nil? + {{/requiredParams}} + {{/requiredParamCount}} + + # set default values and merge with input + options = { + {{#allParams}}:{{{paramName}}} => {{paramName}}{{#hasMore}}, + {{/hasMore}} + {{/allParams}} + }.merge(opts) + + #resource path + path = "{{path}}".sub('{format}','json'){{#pathParams}}.sub('{' + '{{baseName}}' + '}', escapeString({{paramName}})) + {{/pathParams}}{{newline}} + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + {{#headerParams}}headers = { + {{{paramName}}}: {{{paramName}}}, + } + {{/headerParams}} + {{^headerParams}}headers = nil + {{/headerParams}} + + post_body = nil + {{#bodyParam}} + if body != nil + if body.is_a?(Array) + array = Array.new + body.each do |item| + if item.respond_to?("to_body".to_sym) + array.push item.to_body + else + array.push item + end + end + post_body = array + + else + if body.respond_to?("to_body".to_sym) + post_body = body.to_body + else + post_body = body + end + end + end + {{/bodyParam}} + + {{#returnType}} + response = Swagger::Request.new(:{{httpMethod}}, path, {:params=>queryopts,:headers=>headers, :body=>post_body }).make.body + {{#returnContainer}} + response.map {|response|{{/returnContainer}} {{returnBaseType}}.new(response){{#returnContainer}} }{{/returnContainer}} + {{/returnType}} + {{^returnType}} + Swagger::Request.new(:{{httpMethod}}, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make + {{/returnType}} +{{newline}} + end +{{newline}} + {{/operation}} +end +{{/operations}} \ No newline at end of file diff --git a/src/main/resources/ruby/model.mustache b/src/main/resources/ruby/model.mustache new file mode 100644 index 0000000000..eac0d76d4e --- /dev/null +++ b/src/main/resources/ruby/model.mustache @@ -0,0 +1,50 @@ +{{#models}} + +{{#model}} +class {{classname}} + attr_accessor {{#vars}}:{{{name}}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{newline}} + # :internal => :external + def self.attribute_map + { + {{#vars}} + :{{{name}}} => :{{{baseName}}}{{#hasMore}}, {{/hasMore}} + {{/vars}}{{newline}} + } + end + + def initialize(attributes = {}) + # Morph attribute keys into undescored rubyish style + if attributes.to_s != "" + + {{#vars}} + if {{classname}}.attribute_map["{{{name}}}".to_sym] != nil + name = "{{{name}}}".to_sym + value = attributes["{{{baseName}}}"] + + if value.is_a?(Array) + array = Array.new + value.each do |arrayValue| + {{#isPrimitiveType}}array.push arrayValue + {{/isPrimitiveType}} + {{#complexType}}array.push {{complexType}}.new(arrayValue) + {{/complexType}} + end + send("#{name}=", array) if self.respond_to?(name) + else + send("#{name}=", value) if self.respond_to?(name) + end + end + {{/vars}} + end + end + + def to_body + body = {} + {{classname}}.attribute_map.each_pair do |key,value| + body[value] = self.send(key) unless self.send(key).nil? + end + body + end +end +{{/model}} +{{/models}} \ No newline at end of file diff --git a/src/main/resources/ruby/monkey.mustache b/src/main/resources/ruby/monkey.mustache new file mode 100644 index 0000000000..28932890af --- /dev/null +++ b/src/main/resources/ruby/monkey.mustache @@ -0,0 +1,90 @@ +# module Swagger + class Object + + unless Object.method_defined? :blank? + def blank? + respond_to?(:empty?) ? empty? : !self + end + end + + unless Object.method_defined? :present? + def present? + !blank? + end + end + + end + + class String + + unless String.method_defined? :underscore + def underscore + self.gsub(/::/, '/'). + gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). + gsub(/([a-z\d])([A-Z])/,'\1_\2'). + tr("-", "_"). + downcase + end + end + + unless String.method_defined? :camelize + def camelize(first_letter_in_uppercase = true) + if first_letter_in_uppercase != :lower + self.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } + else + self.to_s[0].chr.downcase + camelize(self)[1..-1] + end + end + end + + end + + class Hash + + unless Hash.method_defined? :stringify_keys + def stringify_keys + inject({}) do |options, (key, value)| + options[key.to_s] = value + options + end + end + end + + unless Hash.method_defined? :stringify_keys! + def stringify_keys! + self.replace(self.stringify_keys) + end + end + + unless Hash.method_defined? :symbolize_keys + def symbolize_keys + inject({}) do |options, (key, value)| + options[(key.to_sym rescue key) || key] = value + options + end + end + end + + unless Hash.method_defined? :symbolize_keys! + def symbolize_keys! + self.replace(self.symbolize_keys) + end + end + + unless Hash.method_defined? :symbolize_and_underscore_keys + def symbolize_and_underscore_keys + inject({}) do |options, (key, value)| + options[(key.to_s.underscore.to_sym rescue key) || key] = value + options + end + end + end + + unless Hash.method_defined? :symbolize_and_underscore_keys! + def symbolize_and_underscore_keys! + self.replace(self.symbolize_and_underscore_keys) + end + end + + end +# end \ No newline at end of file diff --git a/src/main/resources/ruby/swagger.mustache b/src/main/resources/ruby/swagger.mustache new file mode 100644 index 0000000000..1cc3ea456c --- /dev/null +++ b/src/main/resources/ruby/swagger.mustache @@ -0,0 +1,84 @@ +require 'monkey' +require 'swagger/configuration' +require 'swagger/request' +require 'swagger/response' +require 'swagger/version' +require 'logger' + +module Swagger + + class << self + attr_accessor :logger + + # 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 + + # 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 + self.configuration ||= Configuration.new + yield(configuration) if block_given? + + # Configure logger. Default to use Rails + self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT)) + + # remove :// from scheme + configuration.scheme.sub!(/:\/\//, '') + + # remove http(s):// and anything after a slash + configuration.host.sub!(/https?:\/\//, '') + configuration.host = configuration.host.split('/').first + + # Add leading and trailing slashes to base_path + configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/') + configuration.base_path = "" if configuration.base_path == "/" + end + + def authenticated? + Swagger.configuration.auth_token.present? + end + + def de_authenticate + Swagger.configuration.auth_token = nil + end + + 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 + +end + +class ServerError < StandardError +end + +class ClientError < StandardError +end \ No newline at end of file diff --git a/src/main/resources/ruby/swagger/configuration.mustache b/src/main/resources/ruby/swagger/configuration.mustache new file mode 100644 index 0000000000..f5d54d1be3 --- /dev/null +++ b/src/main/resources/ruby/swagger/configuration.mustache @@ -0,0 +1,19 @@ +module Swagger + + class Configuration + require 'swagger/version' + + attr_accessor :format, :api_key, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger + + # Defaults go in here.. + def initialize + @format = 'json' + @scheme = 'http' + @host = 'api.wordnik.com' + @base_path = '/v4' + @user_agent = "ruby-#{Swagger::VERSION}" + end + + end + +end \ No newline at end of file diff --git a/src/main/resources/ruby/swagger/request.mustache b/src/main/resources/ruby/swagger/request.mustache new file mode 100644 index 0000000000..1c4326c92e --- /dev/null +++ b/src/main/resources/ruby/swagger/request.mustache @@ -0,0 +1,186 @@ +module Swagger + + class Request + require 'uri' + require 'addressable/uri' + require 'typhoeus' + require "swagger/version" + + attr_accessor :host, :path, :format, :params, :body, :http_method, :headers + + + # 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 + } + + # api_key from headers hash trumps the default, even if its value is blank + if attributes[:headers].present? && attributes[:headers].has_key?(:api_key) + 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 + # + def url(options = {}) + u = Addressable::URI.new( + :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 + # + # e.g. /word.{format}/{word}/entries => /word.json/cat/entries + def interpreted_path + p = self.path.dup + + # Fill in the path params + self.params.each_pair do |key, value| + p = p.gsub("{#{key}}", value.to_s) + end + + # 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 + unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } + p = p.sub(/^(\/?\w+)/, "\\1.#{format}") + 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. + # + def outgoing_body + body.is_a?(String) ? body : body.to_json + end + + # Construct a query string from the query-string-type params + def query_string + + # Iterate over all params, + # .. removing the ones that are part of the path itself. + # .. stringifying values so Addressable doesn't blow up. + query_values = {} + self.params.each_pair do |key, value| + next if self.path.include? "{#{key}}" # skip path params + next if value.blank? && value.class != FalseClass # skip empties + key = key.to_s.camelize(:lower).to_sym unless key.to_sym == :api_key # api_key is not a camelCased param + 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 + 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 :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/, '
') # <- This was for RestClient + @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus + end + + end +end \ No newline at end of file diff --git a/src/main/resources/ruby/swagger/response.mustache b/src/main/resources/ruby/swagger/response.mustache new file mode 100644 index 0000000000..02a1a458eb --- /dev/null +++ b/src/main/resources/ruby/swagger/response.mustache @@ -0,0 +1,70 @@ +module Swagger + + class Response + require 'json' + + attr_accessor :raw + + def initialize(raw) + self.raw = raw + + case self.code + when 500..510 then raise(ServerError, self.error_message) + when 299..426 then raise(ClientError, self.error_message) + 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 + 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/, '
') + end + end + + def pretty_headers + JSON.pretty_generate(headers).gsub(/\n/, '
') + end + + end +end \ No newline at end of file diff --git a/src/main/resources/ruby/swagger/version.mustache b/src/main/resources/ruby/swagger/version.mustache new file mode 100644 index 0000000000..39357c0ed6 --- /dev/null +++ b/src/main/resources/ruby/swagger/version.mustache @@ -0,0 +1,4 @@ +module Swagger + VERSION = "4.06.08" +end +