Avoiding monkey-patching in Ruby API client

This commit is contained in:
xhh 2015-06-26 15:56:59 +08:00
parent 40c9f05536
commit 16e80c65d7
6 changed files with 29 additions and 151 deletions

View File

@ -1,39 +1,3 @@
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
@ -64,19 +28,4 @@ class Hash
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

View File

@ -37,7 +37,7 @@ module {{moduleName}}
end
def authenticated?
Swagger.configuration.auth_token.present?
!Swagger.configuration.auth_token.nil?
end
def de_authenticate
@ -47,7 +47,7 @@ module {{moduleName}}
def authenticate
return if Swagger.authenticated?
if Swagger.configuration.username.blank? || Swagger.configuration.password.blank?
if Swagger.configuration.username.nil? || Swagger.configuration.password.nil?
raise ApiError, "Username and password are required to authenticate."
end

View File

@ -3,7 +3,7 @@ require 'logger'
module {{moduleName}}
module Swagger
class Configuration
attr_accessor :scheme, :host, :base_path, :user_agent, :format, :auth_token, :inject_format, :force_ending_format, :camelize_params
attr_accessor :scheme, :host, :base_path, :user_agent, :format, :auth_token, :inject_format, :force_ending_format
# Defines the username used with HTTP basic authentication.
#
@ -69,7 +69,6 @@ module {{moduleName}}
@user_agent = "ruby-swagger-#{Swagger::VERSION}"
@inject_format = false
@force_ending_format = false
@camelize_params = true
@api_key = {}
@api_key_prefix = {}

View File

@ -1,15 +1,14 @@
require 'uri'
require 'typhoeus'
module {{moduleName}}
module Swagger
class Request
require 'uri'
require 'addressable/uri'
require 'typhoeus'
attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params, :auth_names, :response
# All requests must have an HTTP method and a path
# Optionals parameters are :params, :headers, :body, :format, :host
def initialize(http_method, path, attributes={})
def initialize(http_method, path, attributes = {})
attributes[:format] ||= Swagger.configuration.format
attributes[:params] ||= {}
@ -27,11 +26,10 @@ module {{moduleName}}
attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token})
end
self.http_method = http_method.to_sym
self.http_method = http_method.to_sym.downcase
self.path = path
attributes.each do |name, value|
send("#{name.to_s.underscore.to_sym}=", value)
end
attributes.each { |name, value| send "#{name}=", value }
update_params_for_auth!
end
@ -54,26 +52,18 @@ module {{moduleName}}
# Get API key (with prefix if set).
# @param [String] param_name the parameter name of API key auth
def get_api_key_with_prefix(param_name)
if Swagger.configuration.api_key_prefix[param_name].present?
if Swagger.configuration.api_key_prefix[param_name]
"#{Swagger.configuration.api_key_prefix[param_name]} #{Swagger.configuration.api_key[param_name]}"
else
Swagger.configuration.api_key[param_name]
end
end
# Construct a base URL
# Construct the request 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! /\?$/, ''
u
_path = self.interpreted_path
_path = "/#{_path}" unless _path.start_with?('/')
"#{Swagger.configuration.scheme}://#{Swagger.configuration.host}#{_path}"
end
# Iterate over the params hash, injecting any path values into the path string
@ -104,18 +94,6 @@ module {{moduleName}}
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.
# For form parameters, remove empty value
def outgoing_body
@ -138,70 +116,20 @@ module {{moduleName}}
data
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
if Swagger.configuration.camelize_params
key = key.to_s.camelize(:lower).to_sym
end
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
request_options = {
:method => self.http_method,
:headers => self.headers.stringify_keys,
:ssl_verifypeer => Swagger.configuration.verify_ssl,
:cainfo => Swagger.configuration.ssl_ca_cert,
:headers => self.headers.stringify_keys,
:verbose => Swagger.configuration.debug
}
raw = case self.http_method.to_sym
when :get,:GET
Typhoeus::Request.get(
self.url,
request_options
)
when :post,:POST
Typhoeus::Request.post(
self.url,
request_options.merge(:body => self.outgoing_body)
)
when :patch,:PATCH
Typhoeus::Request.patch(
self.url,
request_options.merge(:body => self.outgoing_body)
)
when :put,:PUT
Typhoeus::Request.put(
self.url,
request_options.merge(:body => self.outgoing_body)
)
when :delete,:DELETE
Typhoeus::Request.delete(
self.url,
request_options.merge(:body => self.outgoing_body)
)
if [:post, :patch, :put, :delete].include?(self.http_method)
request_options.update :body => self.outgoing_body
end
raw = Typhoeus::Request.new(self.url, request_options).run
@response = Response.new(raw)
if Swagger.configuration.debug
@ -217,16 +145,17 @@ module {{moduleName}}
:response_body => @response.body),
@response.status_message
end
@response
end
def response_code_pretty
return unless @response.present?
return unless @response
@response.code.to_s
end
def response_headers_pretty
return unless @response.present?
return unless @response
# JSON.pretty_generate(@response.headers).gsub(/\n/, '<br/>') # <- This was for RestClient
@response.headers.gsub(/\n/, '<br/>') # <- This is for Typhoeus
end

View File

@ -30,7 +30,7 @@ module {{moduleName}}
#
# @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
def deserialize(return_type)
return nil if body.blank?
return nil if body.nil? || body.empty?
# ensuring a default content type
content_type = raw.headers_hash['Content-Type'] || 'application/json'
@ -106,9 +106,11 @@ module {{moduleName}}
end
def pretty_body
return unless body.present?
case format
when 'json' then JSON.pretty_generate(JSON.parse(body)).gsub(/\n/, '<br/>')
return unless body
if format == 'json'
JSON.pretty_generate(JSON.parse(body)).gsub(/\n/, '<br/>')
else
body
end
end

View File

@ -14,7 +14,6 @@ Gem::Specification.new do |s|
s.license = "Apache-2.0"
s.add_runtime_dependency 'typhoeus', '~> 0.2', '>= 0.2.1'
s.add_runtime_dependency 'addressable', '~> 2.2', '>= 2.2.4'
s.add_runtime_dependency 'json', '~> 1.4', '>= 1.4.6'
s.add_development_dependency 'rspec', '~> 3.2', '>= 3.2.0'