rollback ruby template

This commit is contained in:
wing328 2015-06-09 12:33:30 +08:00
parent d5cbbae182
commit 5f6622c70d
7 changed files with 325 additions and 325 deletions

View File

@ -5,14 +5,14 @@ module {{moduleName}}
class {{classname}} class {{classname}}
basePath = "{{basePath}}" basePath = "{{basePath}}"
# apiInvoker = APIInvoker # apiInvoker = APIInvoker
{{#operation}} {{#operation}}
{{newline}} {{newline}}
# {{summary}} # {{summary}}
# {{notes}} # {{notes}}
{{#allParams}}{{#required}} # @param {{paramName}} {{description}} {{#allParams}}{{#required}} # @param {{paramName}} {{description}}
{{/required}}{{/allParams}} # @param [Hash] opts the optional parameters {{/required}}{{/allParams}} # @param [Hash] opts the optional parameters
{{#allParams}}{{^required}} # @option opts [{{dataType}}] :{{paramName}} {{description}} {{#allParams}}{{^required}} # @option opts [{{dataType}}] :{{paramName}} {{description}}
{{/required}}{{/allParams}} # @return [{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}] {{/required}}{{/allParams}} # @return [{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}]
def self.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {}) def self.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {})
{{#allParams}}{{#required}} {{#allParams}}{{#required}}
# verify the required parameter '{{paramName}}' is set # verify the required parameter '{{paramName}}' is set
@ -55,7 +55,7 @@ module {{moduleName}}
{{#returnContainer}}response.map {|response| {{/returnContainer}}obj = {{returnBaseType}}.new() and obj.build_from_hash(response){{#returnContainer}} }{{/returnContainer}}{{/returnType}}{{^returnType}}Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make {{#returnContainer}}response.map {|response| {{/returnContainer}}obj = {{returnBaseType}}.new() and obj.build_from_hash(response){{#returnContainer}} }{{/returnContainer}}{{/returnType}}{{^returnType}}Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil{{/returnType}} nil{{/returnType}}
end end
{{/operation}} {{/operation}}
end end
{{/operations}} {{/operations}}
end end

View File

@ -1,83 +1,83 @@
module {{moduleName}} module {{moduleName}}
# base class containing fundamental method such as to_hash, build_from_hash and more # base class containing fundamental method such as to_hash, build_from_hash and more
class BaseObject class BaseObject
# return the object in the form of hash # return the object in the form of hash
def to_body def to_body
body = {} body = {}
self.class.attribute_map.each_pair do |key, value| self.class.attribute_map.each_pair do |key, value|
body[value] = self.send(key) unless self.send(key).nil? body[value] = self.send(key) unless self.send(key).nil?
end end
body body
end end
# build the object from hash # build the object from hash
def build_from_hash(attributes) def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash) return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type| self.class.swagger_types.each_pair do |key, type|
if type =~ /^array\[(.*)\]/i if type =~ /^array\[(.*)\]/i
if attributes[self.class.attribute_map[key]].is_a?(Array) if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } )
else else
#TODO show warning in debug mode #TODO show warning in debug mode
end end
elsif !attributes[self.class.attribute_map[key]].nil? elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
else else
# data not found in attributes(hash), not an issue as the data can be optional # data not found in attributes(hash), not an issue as the data can be optional
end end
end end
self self
end end
def _deserialize(type, value) def _deserialize(type, value)
case type.to_sym case type.to_sym
when :DateTime when :DateTime
DateTime.parse(value) DateTime.parse(value)
when :string when :string
value.to_s value.to_s
when :int when :int
value.to_i value.to_i
when :double when :double
value.to_f value.to_f
when :boolean when :boolean
if value =~ /^(true|t|yes|y|1)$/i if value =~ /^(true|t|yes|y|1)$/i
true true
else else
false false
end end
else # model else # model
_model = {{moduleName}}.const_get(type).new _model = {{moduleName}}.const_get(type).new
_model.build_from_hash(value) _model.build_from_hash(value)
end end
end end
# to_body is an alias to to_body (backward compatibility) # to_body is an alias to to_body (backward compatibility)
def to_hash def to_hash
hash = {} hash = {}
self.class.attribute_map.each_pair do |key, value| self.class.attribute_map.each_pair do |key, value|
if self.send(key).is_a?(Array) if self.send(key).is_a?(Array)
next if self.send(key).empty? next if self.send(key).empty?
hash[value] = self.send(key).select{|v| !v.nil?}.map{ |v| _to_hash v} unless self.send(key).nil? hash[value] = self.send(key).select{|v| !v.nil?}.map{ |v| _to_hash v} unless self.send(key).nil?
else else
unless (_tmp_value = _to_hash self.send(key)).nil? unless (_tmp_value = _to_hash self.send(key)).nil?
hash[value] = _tmp_value hash[value] = _tmp_value
end end
end end
end end
hash hash
end end
# Method to output non-array value in the form of hash # Method to output non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value # For object, use to_hash. Otherwise, just return the value
def _to_hash(value) def _to_hash(value)
if value.respond_to? :to_hash if value.respond_to? :to_hash
value.to_hash value.to_hash
else else
value value
end end
end end
end end
end end

View File

@ -1,40 +1,40 @@
module {{moduleName}} module {{moduleName}}
{{#models}} # {{description}} {{#models}} # {{description}}
{{#model}} class {{classname}} < BaseObject {{#model}} class {{classname}} < BaseObject
attr_accessor {{#vars}}:{{{name}}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{newline}} attr_accessor {{#vars}}:{{{name}}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{newline}}
# attribute mapping from ruby-style variable name to JSON key # attribute mapping from ruby-style variable name to JSON key
def self.attribute_map def self.attribute_map
{ {
{{#vars}} {{#vars}}
# {{description}} # {{description}}
:'{{{name}}}' => :'{{{baseName}}}'{{#hasMore}},{{/hasMore}} :'{{{name}}}' => :'{{{baseName}}}'{{#hasMore}},{{/hasMore}}
{{/vars}} {{/vars}}
} }
end end
# attribute type # attribute type
def self.swagger_types def self.swagger_types
{ {
{{#vars}}:'{{{name}}}' => :'{{{datatype}}}'{{#hasMore}},{{/hasMore}} {{#vars}}:'{{{name}}}' => :'{{{datatype}}}'{{#hasMore}},{{/hasMore}}
{{/vars}} {{/vars}}
} }
end end
def initialize(attributes = {}) def initialize(attributes = {})
return if !attributes.is_a?(Hash) || attributes.empty? return if !attributes.is_a?(Hash) || attributes.empty?
# convert string to symbol for hash key # convert string to symbol for hash key
attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
{{#vars}} {{#vars}}
if attributes[:'{{{baseName}}}'] if attributes[:'{{{baseName}}}']
{{#isContainer}}if (value = attributes[:'{{{baseName}}}']).is_a?(Array) {{#isContainer}}if (value = attributes[:'{{{baseName}}}']).is_a?(Array)
@{{{name}}} = value @{{{name}}} = value
end{{/isContainer}}{{^isContainer}}@{{{name}}} = attributes[:'{{{baseName}}}']{{/isContainer}} end{{/isContainer}}{{^isContainer}}@{{{name}}} = attributes[:'{{{baseName}}}']{{/isContainer}}
end end
{{/vars}} {{/vars}}
end end
end end
{{/model}} {{/model}}
{{/models}} {{/models}}
end end

View File

@ -1,90 +1,90 @@
# module Swagger # module Swagger
class Object class Object
unless Object.method_defined? :blank? unless Object.method_defined? :blank?
def blank? def blank?
respond_to?(:empty?) ? empty? : !self respond_to?(:empty?) ? empty? : !self
end end
end end
unless Object.method_defined? :present? unless Object.method_defined? :present?
def present? def present?
!blank? !blank?
end end
end end
end end
class String class String
unless String.method_defined? :underscore unless String.method_defined? :underscore
def underscore def underscore
self.gsub(/::/, '/'). self.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_"). tr("-", "_").
downcase downcase
end end
end end
unless String.method_defined? :camelize unless String.method_defined? :camelize
def camelize(first_letter_in_uppercase = true) def camelize(first_letter_in_uppercase = true)
if first_letter_in_uppercase != :lower if first_letter_in_uppercase != :lower
self.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } self.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase }
else else
self.to_s[0].chr.downcase + camelize(self)[1..-1] self.to_s[0].chr.downcase + camelize(self)[1..-1]
end end
end end
end end
end end
class Hash class Hash
unless Hash.method_defined? :stringify_keys unless Hash.method_defined? :stringify_keys
def stringify_keys def stringify_keys
inject({}) do |options, (key, value)| inject({}) do |options, (key, value)|
options[key.to_s] = value options[key.to_s] = value
options options
end end
end end
end end
unless Hash.method_defined? :stringify_keys! unless Hash.method_defined? :stringify_keys!
def stringify_keys! def stringify_keys!
self.replace(self.stringify_keys) self.replace(self.stringify_keys)
end end
end end
unless Hash.method_defined? :symbolize_keys unless Hash.method_defined? :symbolize_keys
def symbolize_keys def symbolize_keys
inject({}) do |options, (key, value)| inject({}) do |options, (key, value)|
options[(key.to_sym rescue key) || key] = value options[(key.to_sym rescue key) || key] = value
options options
end end
end end
end end
unless Hash.method_defined? :symbolize_keys! unless Hash.method_defined? :symbolize_keys!
def symbolize_keys! def symbolize_keys!
self.replace(self.symbolize_keys) self.replace(self.symbolize_keys)
end end
end end
unless Hash.method_defined? :symbolize_and_underscore_keys unless Hash.method_defined? :symbolize_and_underscore_keys
def symbolize_and_underscore_keys def symbolize_and_underscore_keys
inject({}) do |options, (key, value)| inject({}) do |options, (key, value)|
options[(key.to_s.underscore.to_sym rescue key) || key] = value options[(key.to_s.underscore.to_sym rescue key) || key] = value
options options
end end
end end
end end
unless Hash.method_defined? :symbolize_and_underscore_keys! unless Hash.method_defined? :symbolize_and_underscore_keys!
def symbolize_and_underscore_keys! def symbolize_and_underscore_keys!
self.replace(self.symbolize_and_underscore_keys) self.replace(self.symbolize_and_underscore_keys)
end end
end end
end end
# end # end

View File

@ -2,77 +2,77 @@ require 'logger'
require 'json' require 'json'
module {{moduleName}} module {{moduleName}}
module Swagger module Swagger
class << self class << self
attr_accessor :logger attr_accessor :logger
# A Swagger configuration object. Must act like a hash and return sensible # A Swagger configuration object. Must act like a hash and return sensible
# values for all Swagger configuration options. See Swagger::Configuration. # values for all Swagger configuration options. See Swagger::Configuration.
attr_accessor :configuration attr_accessor :configuration
attr_accessor :resources attr_accessor :resources
# Call this method to modify defaults in your initializers. # Call this method to modify defaults in your initializers.
# #
# @example # @example
# Swagger.configure do |config| # Swagger.configure do |config|
# config.api_key['api_key'] = '1234567890abcdef' # api key authentication # config.api_key['api_key'] = '1234567890abcdef' # api key authentication
# config.username = 'wordlover' # http basic authentication # config.username = 'wordlover' # http basic authentication
# config.password = 'i<3words' # http basic authentication # config.password = 'i<3words' # http basic authentication
# config.format = 'json' # optional, defaults to 'json' # config.format = 'json' # optional, defaults to 'json'
# end # end
# #
def configure def configure
yield(configuration) if block_given? yield(configuration) if block_given?
# Configure logger. Default to use Rails # Configure logger. Default to use Rails
self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT)) self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT))
# remove :// from scheme # remove :// from scheme
configuration.scheme.sub!(/:\/\//, '') configuration.scheme.sub!(/:\/\//, '')
# remove http(s):// and anything after a slash # remove http(s):// and anything after a slash
configuration.host.sub!(/https?:\/\//, '') configuration.host.sub!(/https?:\/\//, '')
configuration.host = configuration.host.split('/').first configuration.host = configuration.host.split('/').first
# Add leading and trailing slashes to base_path # Add leading and trailing slashes to base_path
configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/') configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/')
configuration.base_path = "" if configuration.base_path == "/" configuration.base_path = "" if configuration.base_path == "/"
end end
def authenticated? def authenticated?
Swagger.configuration.auth_token.present? Swagger.configuration.auth_token.present?
end end
def de_authenticate def de_authenticate
Swagger.configuration.auth_token = nil Swagger.configuration.auth_token = nil
end end
def authenticate def authenticate
return if Swagger.authenticated? return if Swagger.authenticated?
if Swagger.configuration.username.blank? || Swagger.configuration.password.blank? if Swagger.configuration.username.blank? || Swagger.configuration.password.blank?
raise ClientError, "Username and password are required to authenticate." raise ClientError, "Username and password are required to authenticate."
end end
request = Swagger::Request.new( request = Swagger::Request.new(
:get, :get,
"account/authenticate/{username}", "account/authenticate/{username}",
:params => { :params => {
:username => Swagger.configuration.username, :username => Swagger.configuration.username,
:password => Swagger.configuration.password :password => Swagger.configuration.password
} }
) )
response_body = request.response.body response_body = request.response.body
Swagger.configuration.auth_token = response_body['token'] Swagger.configuration.auth_token = response_body['token']
end end
end end
end end
class ServerError < StandardError class ServerError < StandardError
end end
class ClientError < StandardError class ClientError < StandardError
end end
end end

View File

@ -3,30 +3,30 @@ $:.push File.expand_path("../lib", __FILE__)
require "{{gemName}}/swagger/version" require "{{gemName}}/swagger/version"
Gem::Specification.new do |s| Gem::Specification.new do |s|
s.name = "{{gemName}}" s.name = "{{gemName}}"
s.version = {{moduleName}}::Swagger::VERSION s.version = {{moduleName}}::Swagger::VERSION
s.platform = Gem::Platform::RUBY s.platform = Gem::Platform::RUBY
s.authors = ["Zeke Sikelianos", "Tony Tam"] s.authors = ["Zeke Sikelianos", "Tony Tam"]
s.email = ["zeke@wordnik.com", "fehguy@gmail.com"] s.email = ["zeke@wordnik.com", "fehguy@gmail.com"]
s.homepage = "http://swagger.io" s.homepage = "http://swagger.io"
s.summary = %q{A ruby wrapper for the swagger APIs} s.summary = %q{A ruby wrapper for the swagger APIs}
s.description = %q{This gem maps to a swagger API} s.description = %q{This gem maps to a swagger API}
s.license = "Apache-2.0" s.license = "Apache-2.0"
s.add_runtime_dependency 'typhoeus', '~> 0.2', '>= 0.2.1' s.add_runtime_dependency 'typhoeus', '~> 0.2', '>= 0.2.1'
s.add_runtime_dependency 'addressable', '~> 2.2', '>= 2.2.4' s.add_runtime_dependency 'addressable', '~> 2.2', '>= 2.2.4'
s.add_runtime_dependency 'json', '~> 1.4', '>= 1.4.6' s.add_runtime_dependency 'json', '~> 1.4', '>= 1.4.6'
s.add_development_dependency 'rspec', '~> 3.2', '>= 3.2.0' s.add_development_dependency 'rspec', '~> 3.2', '>= 3.2.0'
s.add_development_dependency 'vcr', '~> 2.9', '>= 2.9.3' s.add_development_dependency 'vcr', '~> 2.9', '>= 2.9.3'
s.add_development_dependency 'webmock', '~> 1.6', '>= 1.6.2' s.add_development_dependency 'webmock', '~> 1.6', '>= 1.6.2'
s.add_development_dependency 'autotest', '~> 4.4', '>= 4.4.6' s.add_development_dependency 'autotest', '~> 4.4', '>= 4.4.6'
s.add_development_dependency 'autotest-rails-pure', '~> 4.1', '>= 4.1.2' s.add_development_dependency 'autotest-rails-pure', '~> 4.1', '>= 4.1.2'
s.add_development_dependency 'autotest-growl', '~> 0.2', '>= 0.2.16' s.add_development_dependency 'autotest-growl', '~> 0.2', '>= 0.2.16'
s.add_development_dependency 'autotest-fsevent', '~> 0.2', '>= 0.2.10' s.add_development_dependency 'autotest-fsevent', '~> 0.2', '>= 0.2.10'
s.files = `find *`.split("\n").uniq.sort.select{|f| !f.empty? } s.files = `find *`.split("\n").uniq.sort.select{|f| !f.empty? }
s.test_files = `find spec/*`.split("\n") s.test_files = `find spec/*`.split("\n")
s.executables = [] s.executables = []
s.require_paths = ["lib"] s.require_paths = ["lib"]
end end

View File

@ -9,17 +9,17 @@ require '{{gemName}}/swagger/version'
# Models # Models
require '{{modelPackage}}/base_object' require '{{modelPackage}}/base_object'
{{#models}} {{#models}}
require '{{importPath}}' require '{{importPath}}'
{{/models}} {{/models}}
# APIs # APIs
{{#apiInfo}} {{#apiInfo}}
{{#apis}} {{#apis}}
require '{{importPath}}' require '{{importPath}}'
{{/apis}} {{/apis}}
{{/apiInfo}} {{/apiInfo}}
module {{moduleName}} module {{moduleName}}
# Initialize the default configuration # Initialize the default configuration
Swagger.configuration ||= Swagger::Configuration.new Swagger.configuration ||= Swagger::Configuration.new
end end