added ruby sample

This commit is contained in:
Tony Tam 2012-09-26 13:02:27 -07:00
parent cbb61b1002
commit 58cfacc4cf
35 changed files with 2666 additions and 0 deletions

19
bin/ruby-petstore.sh Executable file
View File

@ -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

View File

@ -0,0 +1,4 @@
source "http://rubygems.org"
# Specify dependencies in swagger.gemspec
gemspec

View File

@ -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)

View File

@ -0,0 +1,7 @@
require 'bundler'
Bundler::GemHelper.install_tasks
require 'rspec/core/rake_task'
require 'swagger'
RSpec::Core::RakeTask.new('spec')

View File

@ -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")
}

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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/, '<br/>') # <- This was for RestClient
@response.headers.gsub(/\n/, '<br/>') # <- This is for Typhoeus
end
end
end

View File

@ -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/, '<br/>')
end
end
def pretty_headers
JSON.pretty_generate(headers).gsub(/\n/, '<br/>')
end
end
end

View File

@ -0,0 +1,5 @@
module Swagger
VERSION = "4.06.08"
end

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -0,0 +1,4 @@
--colour
--format progress
--loadby mtime
--reverse

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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}}

View File

@ -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}}

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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/, '<br/>') # <- This was for RestClient
@response.headers.gsub(/\n/, '<br/>') # <- This is for Typhoeus
end
end
end

View File

@ -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/, '<br/>')
end
end
def pretty_headers
JSON.pretty_generate(headers).gsub(/\n/, '<br/>')
end
end
end

View File

@ -0,0 +1,4 @@
module Swagger
VERSION = "4.06.08"
end