taxamo-ns 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. checksums.yaml +7 -0
  2. data/Gemfile +7 -0
  3. data/LICENSE +11 -0
  4. data/README.md +152 -0
  5. data/Rakefile +7 -0
  6. data/lib/monkey.rb +90 -0
  7. data/lib/swagger/configuration.rb +21 -0
  8. data/lib/swagger/request.rb +199 -0
  9. data/lib/swagger/response.rb +87 -0
  10. data/lib/swagger.rb +93 -0
  11. data/lib/taxamo/models/additionalcurrencies.rb +63 -0
  12. data/lib/taxamo/models/additionalcurrency.rb +88 -0
  13. data/lib/taxamo/models/bycountry.rb +78 -0
  14. data/lib/taxamo/models/bystatus.rb +70 -0
  15. data/lib/taxamo/models/bytaxationtype.rb +83 -0
  16. data/lib/taxamo/models/c.rb +78 -0
  17. data/lib/taxamo/models/calculatesimpletaxout.rb +75 -0
  18. data/lib/taxamo/models/calculatetaxin.rb +63 -0
  19. data/lib/taxamo/models/calculatetaxlocationout.rb +98 -0
  20. data/lib/taxamo/models/calculatetaxout.rb +75 -0
  21. data/lib/taxamo/models/canceltransactionout.rb +63 -0
  22. data/lib/taxamo/models/capturepaymentout.rb +63 -0
  23. data/lib/taxamo/models/confirmtransactionin.rb +63 -0
  24. data/lib/taxamo/models/confirmtransactionout.rb +75 -0
  25. data/lib/taxamo/models/countries.rb +113 -0
  26. data/lib/taxamo/models/country.rb +120 -0
  27. data/lib/taxamo/models/countryschema.rb +120 -0
  28. data/lib/taxamo/models/createpaymentin.rb +73 -0
  29. data/lib/taxamo/models/createpaymentout.rb +63 -0
  30. data/lib/taxamo/models/createrefundin.rb +83 -0
  31. data/lib/taxamo/models/createrefundout.rb +78 -0
  32. data/lib/taxamo/models/createsmstokenin.rb +68 -0
  33. data/lib/taxamo/models/createsmstokenout.rb +63 -0
  34. data/lib/taxamo/models/createtransactionin.rb +68 -0
  35. data/lib/taxamo/models/createtransactionout.rb +75 -0
  36. data/lib/taxamo/models/currencyschema.rb +83 -0
  37. data/lib/taxamo/models/customfields.rb +68 -0
  38. data/lib/taxamo/models/emailinvoicein.rb +63 -0
  39. data/lib/taxamo/models/emailinvoiceout.rb +63 -0
  40. data/lib/taxamo/models/emailrefundin.rb +63 -0
  41. data/lib/taxamo/models/emailrefundout.rb +63 -0
  42. data/lib/taxamo/models/evidence.rb +113 -0
  43. data/lib/taxamo/models/evidenceschema.rb +78 -0
  44. data/lib/taxamo/models/getcountriesdictout.rb +64 -0
  45. data/lib/taxamo/models/getcurrenciesdictout.rb +64 -0
  46. data/lib/taxamo/models/getdailysettlementstatsout.rb +64 -0
  47. data/lib/taxamo/models/getdetailedrefundsout.rb +64 -0
  48. data/lib/taxamo/models/getdomesticsummaryreportout.rb +123 -0
  49. data/lib/taxamo/models/geteuviesreportout.rb +79 -0
  50. data/lib/taxamo/models/getproducttypesdictout.rb +64 -0
  51. data/lib/taxamo/models/getrefundsout.rb +64 -0
  52. data/lib/taxamo/models/getsettlementout.rb +84 -0
  53. data/lib/taxamo/models/getsettlementstatsbycountryout.rb +64 -0
  54. data/lib/taxamo/models/getsettlementstatsbytaxationtypeout.rb +63 -0
  55. data/lib/taxamo/models/getsettlementsummaryout.rb +63 -0
  56. data/lib/taxamo/models/gettransactionout.rb +75 -0
  57. data/lib/taxamo/models/gettransactionsstatsbycountryout.rb +64 -0
  58. data/lib/taxamo/models/gettransactionsstatsout.rb +63 -0
  59. data/lib/taxamo/models/inputtransaction.rb +220 -0
  60. data/lib/taxamo/models/inputtransactionline.rb +144 -0
  61. data/lib/taxamo/models/inputtransactionupdate.rb +220 -0
  62. data/lib/taxamo/models/invoiceaddress.rb +98 -0
  63. data/lib/taxamo/models/listpaymentsout.rb +64 -0
  64. data/lib/taxamo/models/listrefundsout.rb +64 -0
  65. data/lib/taxamo/models/listtransactionsout.rb +64 -0
  66. data/lib/taxamo/models/locategivenipout.rb +73 -0
  67. data/lib/taxamo/models/locatemyipout.rb +73 -0
  68. data/lib/taxamo/models/n.rb +78 -0
  69. data/lib/taxamo/models/payments.rb +73 -0
  70. data/lib/taxamo/models/producttypeschema.rb +63 -0
  71. data/lib/taxamo/models/refunds.rb +108 -0
  72. data/lib/taxamo/models/report.rb +103 -0
  73. data/lib/taxamo/models/settlementdailystatsschema.rb +103 -0
  74. data/lib/taxamo/models/storagerequiredfields.rb +63 -0
  75. data/lib/taxamo/models/summary.rb +98 -0
  76. data/lib/taxamo/models/taxdataschema.rb +63 -0
  77. data/lib/taxamo/models/taxrequiredfields.rb +63 -0
  78. data/lib/taxamo/models/transaction.rb +330 -0
  79. data/lib/taxamo/models/transactionlines.rb +174 -0
  80. data/lib/taxamo/models/transactions.rb +330 -0
  81. data/lib/taxamo/models/unconfirmtransactionin.rb +63 -0
  82. data/lib/taxamo/models/unconfirmtransactionout.rb +75 -0
  83. data/lib/taxamo/models/updatetransactionin.rb +63 -0
  84. data/lib/taxamo/models/updatetransactionout.rb +75 -0
  85. data/lib/taxamo/models/ustaxexemptioncertificatedetailsschema.rb +139 -0
  86. data/lib/taxamo/models/ustaxexemptioncertificateschema.rb +68 -0
  87. data/lib/taxamo/models/ustaxexemptstate.rb +73 -0
  88. data/lib/taxamo/models/ustaxid.rb +73 -0
  89. data/lib/taxamo/models/validatetaxnumberout.rb +78 -0
  90. data/lib/taxamo/models/verifysmstokenout.rb +63 -0
  91. data/lib/taxamo/version.rb +17 -0
  92. data/lib/taxamo.rb +1215 -0
  93. data/taxamo.gemspec +28 -0
  94. data/test/taxamo/connectivity_test.rb +55 -0
  95. data/test/taxamo/tax_test.rb +152 -0
  96. data/test/taxamo/transactions_api_test.rb +326 -0
  97. metadata +241 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: b21725ba22892284c0782c2349f2a598b4aa4cd4
4
+ data.tar.gz: 0bbb30fd57bcbaabad55f0902fe61f1d7fec02de
5
+ SHA512:
6
+ metadata.gz: 40d2210b0861f2453e9c0de9214fe7b974f42c557d93b6478f70bdc1a8186c669c674d33fb4660dfc02c07201b7155e5e342bcf8286f0eeb62975ce9c66ff424
7
+ data.tar.gz: 798709ed71c9c7b750c2f4efd195b1e32892c9fb53704fd10a4a0eb65baef169ecf515229fab5283de7120be3d7a43d3621b122d858ef191103213f52f81f675
data/Gemfile ADDED
@@ -0,0 +1,7 @@
1
+ source "https://rubygems.org"
2
+ gemspec
3
+
4
+ if Gem::Version.new(RUBY_VERSION.dup) < Gem::Version.new('1.9.3')
5
+ gem 'rest-client', '~> 1.6.8'
6
+ gem 'activesupport', '~> 3.2'
7
+ end
data/LICENSE ADDED
@@ -0,0 +1,11 @@
1
+ Copyright 2014-2016 Taxamo, Ltd.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at [apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
6
+
7
+ Unless required by applicable law or agreed to in writing, software
8
+ distributed under the License is distributed on an "AS IS" BASIS,
9
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ See the License for the specific language governing permissions and
11
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,152 @@
1
+ # Taxamo API Ruby client
2
+
3
+ This package provides [Taxamo](http://www.taxamo.com) API bindings for Ruby and was generated using Swagger-codegen.
4
+
5
+ ## Installation
6
+
7
+ To install it, just fetch this repository and issue the following command:
8
+
9
+ ```shell
10
+ $ gem build taxamo.gemspec
11
+ $ gem install taxamo-ns-2.2.0.gem
12
+ ```
13
+
14
+ Alternatively, add the following line to your project's `Gemfile` file:
15
+
16
+ ```ruby
17
+ gem "taxamo-ns", github: "taxamo/taxamo-ruby", '~> 2.0'
18
+ ```
19
+
20
+ If your code relies on 1.x version and uses the classes for constructing input, without the namespaces, you can keep on using it:
21
+
22
+ ```ruby
23
+ gem "taxamo", github: "taxamo/taxamo-ruby", '~> 1.1'
24
+ ```
25
+
26
+ ## Changes
27
+
28
+ 2.2.0 (2017-05-03):
29
+ * rename the gem to taxamo-ns to distinguish it from non-namespaced version
30
+
31
+ 2.1.0 (2017-05-03):
32
+ * bring API client up-to-date with current api endpoints. Please note that the following methods have their arity changed: `get_eu_vies_report`, `get_settlement`, `list_transactions`.
33
+
34
+ 2.0.1 (2016-05-23):
35
+ * bring dependencies up-to-date
36
+
37
+ 2.0.0 (2016-05-20):
38
+ * introduce namespaces to taxamo.models.*
39
+ * send a Source-Id header in all HTTP requests. The header will contain current library version.
40
+
41
+ 1.1.1 (2016-05-17):
42
+ * bring API client up-to-date with current api endpoints. Please note that the following methods have their arity changed: `list_transactions`
43
+
44
+ 1.1.0 (2015-10-13):
45
+ * update API client with multiple region support. Please note that the following methods have their arity changed:
46
+ `list_transactions`, `calculate_simple_tax`, `get_refunds`, `get_settlement`, `get_settlement_summary`
47
+
48
+ 1.0.6.1 (2015-07-20):
49
+ * fix for rubygems.org publishing issue
50
+
51
+ 1.0.6 (2015-07-20):
52
+ * fix regression with require_rel
53
+
54
+ 1.0.5 (2015-07-02):
55
+ * sync with the newest API model, including addition of getsettlementdailystats operation
56
+
57
+ 1.0.4 (2015-04-15):
58
+ * sync with the newest API data model, including unconfirm transaction and email invoice operations and a default currency code for each country
59
+ * please note, that the list_transactions operation has new argument: invoice_number, changing the argument count to 12
60
+
61
+ 1.0.3 (2015-04-15):
62
+ * use require_rel to make the require work properly when using bundler to manage the dependencies
63
+
64
+ 1.0.2 (2015-03-16):
65
+ * Refresh CreateRefundOut with new field and updated documentation
66
+
67
+ 1.0.1:
68
+
69
+ * Added buyer_tax_number_valid field to tax calculation, transaction storage and VAT number validation operations
70
+ * Added key_or_custom_id to list_transactions operation - please note, that the number of arguments has changed!
71
+
72
+ ## Usage
73
+
74
+ First of all, you need to set your private test or live token:
75
+
76
+ ```ruby
77
+ require 'taxamo'
78
+
79
+ Swagger.configure do |config|
80
+ config.api_key = 'YOUR_TOKEN_HERE'
81
+ end
82
+ ```
83
+
84
+ Next, you can invoke the API as functions in Taxamo module:
85
+
86
+ ```ruby
87
+ resp = Taxamo.get_transaction('SOME_TRANSACTION_ID')
88
+ ```
89
+
90
+ It is possible to use hashes and arrays as input:
91
+
92
+ ```ruby
93
+ resp = Taxamo.calculate_tax(
94
+ {'transaction' => {
95
+ 'currency_code' => 'USD',
96
+ 'buyer_ip' => '127.0.0.1',
97
+ 'billing_country_code' => 'IE',
98
+ 'force_country_code' => 'FR',
99
+ 'transaction_lines' => [{'amount' => 200,
100
+ 'custom_id' => 'line1'},
101
+ {'amount' => 100,
102
+ 'product_type' => 'e-book',
103
+ 'custom_id' => 'line2'}]}})
104
+ ```
105
+
106
+ But also regular classes:
107
+
108
+ ```ruby
109
+ taxIn = Taxamo::CalculateTaxIn.new
110
+ taxIn.transaction = Taxamo::InputTransaction.new
111
+ taxIn.transaction.currency_code = 'USD'
112
+ taxIn.transaction.buyer_ip = '127.0.0.1'
113
+ taxIn.transaction.billing_country_code = 'IE'
114
+ taxIn.transaction.force_country_code = 'FR'
115
+ taxIn.transaction.transaction_lines = [Taxamo::InputTransactionLine.new, Taxamo::InputTransactionLine.new]
116
+ taxIn.transaction.transaction_lines[0].amount = 200
117
+ taxIn.transaction.transaction_lines[0].custom_id = 'line1'
118
+ taxIn.transaction.transaction_lines[1].amount = 100
119
+ taxIn.transaction.transaction_lines[1].custom_id = 'line2'
120
+ taxIn.transaction.transaction_lines[1].product_type = 'e-book'
121
+
122
+ resp = Taxamo.calculate_tax(taxIn)
123
+ ```
124
+
125
+ The output is always coerced to appropriate classes:
126
+
127
+ ```ruby
128
+ assert_equal resp.transaction.countries.detected.code, 'IE'
129
+ assert_equal resp.transaction.amount, 300
130
+ assert_equal resp.transaction.tax_amount, 45.5
131
+ assert_equal resp.transaction.total_amount, 345.5
132
+ ```
133
+
134
+ See the regression tests for more examples.
135
+
136
+ ## Documentation
137
+
138
+ Please see http://www.taxamo.com/documentation/ for the most up-to-date documentation.
139
+
140
+ ## License
141
+
142
+ Copyright 2014-2016 Taxamo, Ltd.
143
+
144
+ Licensed under the Apache License, Version 2.0 (the "License");
145
+ you may not use this file except in compliance with the License.
146
+ You may obtain a copy of the License at [apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
147
+
148
+ Unless required by applicable law or agreed to in writing, software
149
+ distributed under the License is distributed on an "AS IS" BASIS,
150
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
151
+ See the License for the specific language governing permissions and
152
+ limitations under the License.
data/Rakefile ADDED
@@ -0,0 +1,7 @@
1
+ require 'rake/testtask'
2
+
3
+ task :default => [:test]
4
+
5
+ Rake::TestTask.new do |t|
6
+ t.pattern = './test/**/*_test.rb'
7
+ end
data/lib/monkey.rb ADDED
@@ -0,0 +1,90 @@
1
+ # module Swagger
2
+ class Object
3
+
4
+ unless Object.method_defined? :blank?
5
+ def blank?
6
+ respond_to?(:empty?) ? empty? : !self
7
+ end
8
+ end
9
+
10
+ unless Object.method_defined? :present?
11
+ def present?
12
+ !blank?
13
+ end
14
+ end
15
+
16
+ end
17
+
18
+ class String
19
+
20
+ unless String.method_defined? :underscore
21
+ def underscore
22
+ self.gsub(/::/, '/').
23
+ gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
24
+ gsub(/([a-z\d])([A-Z])/,'\1_\2').
25
+ tr("-", "_").
26
+ downcase
27
+ end
28
+ end
29
+
30
+ unless String.method_defined? :camelize
31
+ def camelize(first_letter_in_uppercase = true)
32
+ if first_letter_in_uppercase != :lower
33
+ self.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase }
34
+ else
35
+ self.to_s[0].chr.downcase + camelize(self)[1..-1]
36
+ end
37
+ end
38
+ end
39
+
40
+ end
41
+
42
+ class Hash
43
+
44
+ unless Hash.method_defined? :stringify_keys
45
+ def stringify_keys
46
+ inject({}) do |options, (key, value)|
47
+ options[key.to_s] = value
48
+ options
49
+ end
50
+ end
51
+ end
52
+
53
+ unless Hash.method_defined? :stringify_keys!
54
+ def stringify_keys!
55
+ self.replace(self.stringify_keys)
56
+ end
57
+ end
58
+
59
+ unless Hash.method_defined? :symbolize_keys
60
+ def symbolize_keys
61
+ inject({}) do |options, (key, value)|
62
+ options[(key.to_sym rescue key) || key] = value
63
+ options
64
+ end
65
+ end
66
+ end
67
+
68
+ unless Hash.method_defined? :symbolize_keys!
69
+ def symbolize_keys!
70
+ self.replace(self.symbolize_keys)
71
+ end
72
+ end
73
+
74
+ unless Hash.method_defined? :symbolize_and_underscore_keys
75
+ def symbolize_and_underscore_keys
76
+ inject({}) do |options, (key, value)|
77
+ options[(key.to_s.underscore.to_sym rescue key) || key] = value
78
+ options
79
+ end
80
+ end
81
+ end
82
+
83
+ unless Hash.method_defined? :symbolize_and_underscore_keys!
84
+ def symbolize_and_underscore_keys!
85
+ self.replace(self.symbolize_and_underscore_keys)
86
+ end
87
+ end
88
+
89
+ end
90
+ # end
@@ -0,0 +1,21 @@
1
+ module Swagger
2
+
3
+ class Configuration
4
+
5
+ attr_accessor :format, :api_key, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params
6
+
7
+ # Defaults go in here..
8
+ def initialize
9
+ @format = 'json'
10
+ @scheme = 'https'
11
+ @host = 'api.taxamo.com'
12
+ @base_path = ''
13
+ @user_agent = "ruby-swagger"
14
+ @inject_format = true
15
+ @force_ending_format = false
16
+ @camelize_params = false
17
+ end
18
+
19
+ end
20
+
21
+ end
@@ -0,0 +1,199 @@
1
+ module Swagger
2
+
3
+ class Request
4
+ require 'uri'
5
+ require 'addressable/uri'
6
+ require 'typhoeus'
7
+
8
+ attr_accessor :host, :path, :format, :params, :body, :http_method, :headers
9
+
10
+
11
+ # All requests must have an HTTP method and a path
12
+ # Optionals parameters are :params, :headers, :body, :format, :host
13
+ #
14
+ def initialize(http_method, path, attributes={})
15
+ attributes[:format] ||= Swagger.configuration.format
16
+ attributes[:params] ||= {}
17
+
18
+ # Set default headers
19
+ default_headers = {
20
+ 'Content-Type' => "application/#{attributes[:format].downcase}",
21
+ 'Token' => Swagger.configuration.api_key,
22
+ 'Source-Id' => "taxamo-ruby/" + Taxamo::VERSION
23
+ }
24
+
25
+ # api_key from headers hash trumps the default, even if its value is blank
26
+ if attributes[:headers].present? && attributes[:headers].has_key?(:api_key)
27
+ default_headers.delete(:api_key)
28
+ end
29
+
30
+ # api_key from params hash trumps all others (headers and default_headers)
31
+ if attributes[:params].present? && attributes[:params].has_key?(:api_key)
32
+ default_headers.delete(:api_key)
33
+ attributes[:headers].delete(:api_key) if attributes[:headers].present?
34
+ end
35
+
36
+ # Merge argument headers into defaults
37
+ attributes[:headers] = default_headers.merge(attributes[:headers] || {})
38
+
39
+ # Stick in the auth token if there is one
40
+ if Swagger.authenticated?
41
+ attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token})
42
+ end
43
+
44
+ self.http_method = http_method.to_sym
45
+ self.path = path
46
+ attributes.each do |name, value|
47
+ send("#{name.to_s.underscore.to_sym}=", value)
48
+ end
49
+ end
50
+
51
+ # Construct a base URL
52
+ #
53
+ def url(options = {})
54
+ u = Addressable::URI.new(
55
+ :scheme => Swagger.configuration.scheme,
56
+ :host => Swagger.configuration.host,
57
+ :path => self.interpreted_path,
58
+ :query => self.query_string.sub(/\?/, '')
59
+ ).to_s
60
+
61
+ # Drop trailing question mark, if present
62
+ u.sub! /\?$/, ''
63
+
64
+ # Obfuscate API key?
65
+ u.sub! /api\_key=\w+/, 'api_key=YOUR_API_KEY' if options[:obfuscated]
66
+
67
+ u
68
+ end
69
+
70
+ # Iterate over the params hash, injecting any path values into the path string
71
+ #
72
+ # e.g. /word.{format}/{word}/entries => /word.json/cat/entries
73
+ def interpreted_path
74
+ p = self.path.dup
75
+
76
+ # Fill in the path params
77
+ self.params.each_pair do |key, value|
78
+ p = p.gsub("{#{key}}", value.to_s)
79
+ end
80
+
81
+ # # Stick a .{format} placeholder into the path if there isn't
82
+ # # one already or an actual format like json or xml
83
+ # # e.g. /words/blah => /words.{format}/blah
84
+ # if Swagger.configuration.inject_format
85
+ # unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s }
86
+ # p = p.sub(/^(\/?\w+)/, "\\1.#{format}")
87
+ # end
88
+ # end
89
+ #
90
+ # # Stick a .{format} placeholder on the end of the path if there isn't
91
+ # # one already or an actual format like json or xml
92
+ # # e.g. /words/blah => /words/blah.{format}
93
+ # if Swagger.configuration.force_ending_format
94
+ # unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s }
95
+ # p = "#{p}.#{format}"
96
+ # end
97
+ # end
98
+ #
99
+ # p = p.sub("{format}", self.format.to_s)
100
+ #
101
+ URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/')
102
+ end
103
+
104
+ # Massage the request body into a state of readiness
105
+ # If body is a hash, camelize all keys then convert to a json string
106
+ #
107
+ def body=(value)
108
+ if value.is_a?(Hash)
109
+ value = value.inject({}) do |memo, (k,v)|
110
+ memo[k.to_s.camelize(:lower).to_sym] = v
111
+ memo
112
+ end
113
+ end
114
+ @body = value
115
+ end
116
+
117
+ # If body is an object, JSONify it before making the actual request.
118
+ #
119
+ def outgoing_body
120
+ body.is_a?(String) ? body : body.to_json
121
+ end
122
+
123
+ # Construct a query string from the query-string-type params
124
+ def query_string
125
+
126
+ # Iterate over all params,
127
+ # .. removing the ones that are part of the path itself.
128
+ # .. stringifying values so Addressable doesn't blow up.
129
+ query_values = {}
130
+ self.params.each_pair do |key, value|
131
+ next if self.path.include? "{#{key}}" # skip path params
132
+ next if value.blank? && value.class != FalseClass # skip empties
133
+ if Swagger.configuration.camelize_params
134
+ key = key.to_s.camelize(:lower).to_sym unless key.to_sym == :api_key # api_key is not a camelCased param
135
+ end
136
+ query_values[key.to_s] = value.to_s
137
+ end
138
+
139
+ # We don't want to end up with '?' as our query string
140
+ # if there aren't really any params
141
+ return "" if query_values.blank?
142
+
143
+ # Addressable requires query_values to be set after initialization..
144
+ qs = Addressable::URI.new
145
+ qs.query_values = query_values
146
+ qs.to_s
147
+ end
148
+
149
+ def make
150
+ logger = Logger.new STDOUT
151
+ logger.debug self.url
152
+ response = case self.http_method.to_sym
153
+ when :get,:GET
154
+ Typhoeus::Request.get(
155
+ self.url,
156
+ :headers => self.headers.stringify_keys,
157
+ )
158
+
159
+ when :post,:POST
160
+ Typhoeus::Request.post(
161
+ self.url,
162
+ :body => self.outgoing_body,
163
+ :headers => self.headers.stringify_keys,
164
+ )
165
+
166
+ when :put,:PUT
167
+ Typhoeus::Request.put(
168
+ self.url,
169
+ :body => self.outgoing_body,
170
+ :headers => self.headers.stringify_keys,
171
+ )
172
+
173
+ when :delete,:DELETE
174
+ Typhoeus::Request.delete(
175
+ self.url,
176
+ :body => self.outgoing_body,
177
+ :headers => self.headers.stringify_keys,
178
+ )
179
+ end
180
+ Response.new(response)
181
+ end
182
+
183
+ def response
184
+ self.make
185
+ end
186
+
187
+ def response_code_pretty
188
+ return unless @response.present?
189
+ @response.code.to_s
190
+ end
191
+
192
+ def response_headers_pretty
193
+ return unless @response.present?
194
+ # JSON.pretty_generate(@response.headers).gsub(/\n/, '<br/>') # <- This was for RestClient
195
+ @response.headers.gsub(/\n/, '<br/>') # <- This is for Typhoeus
196
+ end
197
+
198
+ end
199
+ end
@@ -0,0 +1,87 @@
1
+ module Swagger
2
+
3
+ class Response
4
+ require 'json'
5
+
6
+ attr_accessor :raw
7
+
8
+ def initialize(raw)
9
+ self.raw = raw
10
+
11
+ case self.code
12
+ when 500..510 then raise(ServerError, self.body)
13
+ when 400 then
14
+ e = nil
15
+ if self.body['errors']
16
+ e = ValidationError.new(self.body['errors'])
17
+ if self.body['validation_failures']
18
+ e.validation_failures = self.body['validation_failures']
19
+ end
20
+ else
21
+ e = ValidationError.new(self.body)
22
+ end
23
+ raise(e)
24
+ when 401 then raise(AuthenticationError, self.body)
25
+ when 402..403 then raise(ClientError, self.body)
26
+ when 299..399 then raise(ClientError, self.body)
27
+ when 0 then raise(ClientError, raw.return_message)
28
+ end
29
+ end
30
+
31
+ def code
32
+ raw.code
33
+ end
34
+
35
+ # Account for error messages that take different forms...
36
+ def error_message
37
+ body['message']
38
+ rescue
39
+ body
40
+ end
41
+
42
+ def validation_message
43
+ body
44
+ end
45
+ # If body is JSON, parse it
46
+ # Otherwise return raw string
47
+ def body
48
+ JSON.parse raw.body
49
+ rescue
50
+ raw.body
51
+ end
52
+
53
+ # `headers_hash` is a Typhoeus-specific extension of Hash,
54
+ # so simplify it back into a regular old Hash.
55
+ def headers
56
+ h = {}
57
+ raw.headers_hash.each {|k,v| h[k] = v }
58
+ h
59
+ end
60
+
61
+ # Extract the response format from the header hash
62
+ # e.g. {'Content-Type' => 'application/json'}
63
+ def format
64
+ headers['Content-Type'].split("/").last.downcase
65
+ end
66
+
67
+ def json?
68
+ format == 'json'
69
+ end
70
+
71
+ def xml?
72
+ format == 'xml'
73
+ end
74
+
75
+ def pretty_body
76
+ return unless body.present?
77
+ case format
78
+ when 'json' then JSON.pretty_generate(body).gsub(/\n/, '<br/>')
79
+ end
80
+ end
81
+
82
+ def pretty_headers
83
+ JSON.pretty_generate(headers).gsub(/\n/, '<br/>')
84
+ end
85
+
86
+ end
87
+ end
data/lib/swagger.rb ADDED
@@ -0,0 +1,93 @@
1
+ require 'monkey'
2
+ require 'swagger/configuration'
3
+ require 'swagger/request'
4
+ require 'swagger/response'
5
+ require 'logger'
6
+
7
+ module Swagger
8
+
9
+ class << self
10
+ attr_accessor :logger
11
+
12
+ # A Swagger configuration object. Must act like a hash and return sensible
13
+ # values for all Swagger configuration options. See Swagger::Configuration.
14
+ attr_accessor :configuration
15
+
16
+ attr_accessor :resources
17
+
18
+ # Call this method to modify defaults in your initializers.
19
+ #
20
+ # @example
21
+ # Swagger.configure do |config|
22
+ # config.api_key = '1234567890abcdef' # required
23
+ # config.username = 'wordlover' # optional, but needed for user-related functions
24
+ # config.password = 'i<3words' # optional, but needed for user-related functions
25
+ # config.format = 'json' # optional, defaults to 'json'
26
+ # end
27
+ #
28
+ def configure
29
+ self.configuration ||= Configuration.new
30
+ yield(configuration) if block_given?
31
+
32
+ # Configure logger. Default to use Rails
33
+ self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT))
34
+
35
+ # remove :// from scheme
36
+ configuration.scheme.sub!(/:\/\//, '')
37
+
38
+ # remove http(s):// and anything after a slash
39
+ configuration.host.sub!(/https?:\/\//, '')
40
+ configuration.host = configuration.host.split('/').first
41
+
42
+ # Add leading and trailing slashes to base_path
43
+ configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/')
44
+ configuration.base_path = "" if configuration.base_path == "/"
45
+ end
46
+
47
+ def authenticated?
48
+ Swagger.configuration.auth_token.present?
49
+ end
50
+
51
+ def de_authenticate
52
+ Swagger.configuration.auth_token = nil
53
+ end
54
+
55
+ def authenticate
56
+ return if Swagger.authenticated?
57
+
58
+ if Swagger.configuration.username.blank? || Swagger.configuration.password.blank?
59
+ raise ClientError, "Username and password are required to authenticate."
60
+ end
61
+
62
+ request = Swagger::Request.new(
63
+ :get,
64
+ "account/authenticate/{username}",
65
+ :params => {
66
+ :username => Swagger.configuration.username,
67
+ :password => Swagger.configuration.password
68
+ }
69
+ )
70
+
71
+ response_body = request.response.body
72
+ Swagger.configuration.auth_token = response_body['token']
73
+ end
74
+
75
+ end
76
+
77
+ end
78
+
79
+ class ServerError < StandardError
80
+ end
81
+
82
+ class ValidationError < StandardError
83
+ attr_accessor :validation_failures
84
+ end
85
+
86
+ class NotFoundError < StandardError
87
+ end
88
+
89
+ class AuthenticationError < StandardError
90
+ end
91
+
92
+ class ClientError < StandardError
93
+ end