zendesk_api 1.13.4 → 1.29.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
- SHA1:
3
- metadata.gz: 929e97f4f95119eb52613dd21e7bcdfdf812d880
4
- data.tar.gz: f6befca8e106dc2946d431ec7dbefafaca698db6
2
+ SHA256:
3
+ metadata.gz: 592ae735c6f79aa698f4edcd7328c5774dcffc06c00e2f28b85027586f98a48c
4
+ data.tar.gz: a86e4f2d88eb2b6a05082ba5bd343942dc645af19dcfbd75d00c1ccf1e8d08fe
5
5
  SHA512:
6
- metadata.gz: 03043ac68eb0208d90dbf7757200270e29ea7e8e5341fc0dac9a1ca5b739c662ebff110ebd2a2bfbce0dad79e2b11aab0a0b6559e16105b41d7ca65733a9902d
7
- data.tar.gz: 462327e6ac915c8bc83f7e921d4198366ea2484c1b9d8e3958870c56e0fc97adf9ca9162537f2a1bf84c9fddc0b1c1fc0aa37cce1938d9f774dff89bd7e98def
6
+ metadata.gz: b4563b95cd57c46662876c012fcabcee71b35d39d77d93f7e36fe629f46187c001e8c817c06004fb7617c5c1c9191f0c0c8bc40662e15d550cc7721c89341822
7
+ data.tar.gz: 21ebc067a097717124234eae951a8f7d8e003076e6af8958404b2e26dc0b5b08acdb3c26f1792380441802aee21f23632850338e81bb6657948990d4ddfe5aba
data/LICENSE ADDED
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
@@ -72,7 +72,7 @@ module ZendeskAPI
72
72
  changed = association.is_a?(Collection) || association.changed?
73
73
 
74
74
  if association.respond_to?(:save) && changed && !inline_creation && association.save
75
- self.send("#{association_name}=", association) # set id/ids columns
75
+ send("#{association_name}=", association) # set id/ids columns
76
76
  end
77
77
 
78
78
  if (association_data[:inline] == true || inline_creation) && changed
@@ -129,7 +129,7 @@ module ZendeskAPI
129
129
  # @param [Hash] options Any additional GET parameters to be added
130
130
  def find(client, options = {}, &block)
131
131
  find!(client, options, &block)
132
- rescue ZendeskAPI::Error::ClientError => e
132
+ rescue ZendeskAPI::Error::ClientError
133
133
  nil
134
134
  end
135
135
  end
@@ -181,6 +181,41 @@ module ZendeskAPI
181
181
  end
182
182
  end
183
183
 
184
+ module CreateOrUpdate
185
+ # Creates or updates resource using the create_or_update endpoint.
186
+ # @param [Client] client The {Client} object to be used
187
+ # @param [Hash] attributes The attributes to create.
188
+ def create_or_update!(client, attributes, association = Association.new(:class => self))
189
+ response = client.connection.post("#{association.generate_path}/create_or_update") do |req|
190
+ req.body = { singular_resource_name => attributes }
191
+
192
+ yield req if block_given?
193
+ end
194
+
195
+ new_from_response(client, response, Array(association.options[:include]))
196
+ end
197
+ end
198
+
199
+ module CreateOrUpdateMany
200
+ # Creates or updates multiple resources using the create_or_update_many endpoint.
201
+ #
202
+ # @param [Client] client The {Client} object to be used
203
+ # @param [Array<Hash>] attributes The attributes to update resources with
204
+ #
205
+ # @return [JobStatus] the {JobStatus} instance for this destroy job
206
+ def create_or_update_many!(client, attributes)
207
+ association = Association.new(:class => self)
208
+
209
+ response = client.connection.post("#{association.generate_path}/create_or_update_many") do |req|
210
+ req.body = { resource_name => attributes }
211
+
212
+ yield req if block_given?
213
+ end
214
+
215
+ JobStatus.new_from_response(client, response)
216
+ end
217
+ end
218
+
184
219
  module Destroy
185
220
  def self.included(klass)
186
221
  klass.extend(ClassMethod)
@@ -276,15 +311,19 @@ module ZendeskAPI
276
311
  module UpdateMany
277
312
  # Updates multiple resources using the update_many endpoint.
278
313
  # @param [Client] client The {Client} object to be used
279
- # @param [Array] ids An array of ids to update
314
+ # @param [Array] ids_or_attributes An array of ids or arributes including ids to update
280
315
  # @param [Hash] attributes The attributes to update resources with
281
316
  # @return [JobStatus] the {JobStatus} instance for this destroy job
282
- def update_many!(client, ids, attributes)
317
+ def update_many!(client, ids_or_attributes, attributes = {})
283
318
  association = attributes.delete(:association) || Association.new(:class => self)
284
319
 
285
320
  response = client.connection.put("#{association.generate_path}/update_many") do |req|
286
- req.params = { :ids => ids.join(',') }
287
- req.body = { singular_resource_name => attributes }
321
+ if attributes == {}
322
+ req.body = { resource_name => ids_or_attributes }
323
+ else
324
+ req.params = { :ids => ids_or_attributes.join(',') }
325
+ req.body = { singular_resource_name => attributes }
326
+ end
288
327
 
289
328
  yield req if block_given?
290
329
  end
@@ -37,7 +37,7 @@ module ZendeskAPI
37
37
  # * parent - Parent instance
38
38
  # * path - Optional path instead of resource name
39
39
  def initialize(options = {})
40
- @options = Hashie::Mash.new(options)
40
+ @options = SilentMash.new(options)
41
41
  end
42
42
 
43
43
  # Generate a path to the resource.
@@ -48,7 +48,7 @@ module ZendeskAPI
48
48
  # * with_parent - Include the parent path (false by default)
49
49
  # * with_id - Include the instance id, if possible (true)
50
50
  def generate_path(*args)
51
- options = Hashie::Mash.new(:with_id => true)
51
+ options = SilentMash.new(:with_id => true)
52
52
  if args.last.is_a?(Hash)
53
53
  original_options = args.pop
54
54
  options.merge!(original_options)
@@ -150,7 +150,7 @@ module ZendeskAPI
150
150
  def build_parent_namespace(parent_class, instance, options, original_options)
151
151
  path = @options.path
152
152
 
153
- association_on_parent = parent_class.associations.detect {|a| a[:name] == @options[:name]}
153
+ association_on_parent = parent_class.associations.detect { |a| a[:name] == @options[:name] }
154
154
  association_on_parent ||= parent_class.associations.detect do |a|
155
155
  !a[:inline] && a[:class] == @options[:class]
156
156
  end
@@ -20,7 +20,7 @@ module ZendeskAPI
20
20
  case resource
21
21
  when Hash
22
22
  klass.new(@client, resource.merge(:association => instance_association))
23
- when String, Fixnum
23
+ when String, Integer
24
24
  klass.new(@client, (options[:include_key] || :id) => resource, :association => instance_association)
25
25
  else
26
26
  resource.association = instance_association
@@ -172,7 +172,7 @@ module ZendeskAPI
172
172
  klass.find(@client, :id => id, :association => instance_association)
173
173
  end.compact
174
174
  elsif (resources = method_missing(association[:name].to_sym)) && resources.any?
175
- resources.map {|res| wrap_resource(res, association)}
175
+ resources.map { |res| wrap_resource(res, association) }
176
176
  else
177
177
  []
178
178
  end
@@ -5,8 +5,10 @@ require 'zendesk_api/sideloading'
5
5
  require 'zendesk_api/configuration'
6
6
  require 'zendesk_api/collection'
7
7
  require 'zendesk_api/lru_cache'
8
+ require 'zendesk_api/silent_mash'
8
9
  require 'zendesk_api/middleware/request/etag_cache'
9
10
  require 'zendesk_api/middleware/request/retry'
11
+ require 'zendesk_api/middleware/request/raise_rate_limited'
10
12
  require 'zendesk_api/middleware/request/upload'
11
13
  require 'zendesk_api/middleware/request/encode_json'
12
14
  require 'zendesk_api/middleware/request/url_based_access_token'
@@ -63,7 +65,7 @@ module ZendeskAPI
63
65
  # @return [Hash] The attributes of the current account or nil
64
66
  def current_account(reload = false)
65
67
  return @current_account if @current_account && !reload
66
- @current_account = Hashie::Mash.new(connection.get('account/resolve').body)
68
+ @current_account = SilentMash.new(connection.get('account/resolve').body)
67
69
  end
68
70
 
69
71
  # Returns the current locale
@@ -92,6 +94,8 @@ module ZendeskAPI
92
94
 
93
95
  config.retry = !!config.retry # nil -> false
94
96
 
97
+ set_raise_error_when_rated_limited
98
+
95
99
  set_token_auth
96
100
 
97
101
  set_default_logger
@@ -170,9 +174,14 @@ module ZendeskAPI
170
174
  builder.use ZendeskAPI::Middleware::Request::Upload
171
175
  builder.request :multipart
172
176
  builder.use ZendeskAPI::Middleware::Request::EncodeJson
173
- builder.use ZendeskAPI::Middleware::Request::Retry, :logger => config.logger if config.retry # Should always be first in the stack
174
177
 
175
- builder.adapter *adapter
178
+ # Should always be first in the stack
179
+ builder.use ZendeskAPI::Middleware::Request::Retry, :logger => config.logger if config.retry
180
+ if config.raise_error_when_rate_limited
181
+ builder.use ZendeskAPI::Middleware::Request::RaiseRateLimited, :logger => config.logger
182
+ end
183
+
184
+ builder.adapter(*adapter)
176
185
  end
177
186
  end
178
187
 
@@ -189,8 +198,20 @@ module ZendeskAPI
189
198
  end
190
199
  end
191
200
 
201
+ def set_raise_error_when_rated_limited
202
+ config.raise_error_when_rate_limited = if config.retry
203
+ false
204
+ else
205
+ !!config.raise_error_when_rate_limited
206
+ end
207
+ end
208
+
192
209
  def set_token_auth
193
- if config.token && !config.password
210
+ return if config.password || config.token.nil?
211
+
212
+ if config.username.nil?
213
+ raise ArgumentError, "you need to provide a username when using API token auth"
214
+ else
194
215
  config.password = config.token
195
216
  config.username += "/token" unless config.username.end_with?("/token")
196
217
  end
@@ -29,7 +29,7 @@ module ZendeskAPI
29
29
  # @param [Hash] options Any additional options to be passed in.
30
30
  def initialize(client, resource, options = {})
31
31
  @client, @resource_class, @resource = client, resource, resource.resource_name
32
- @options = Hashie::Mash.new(options)
32
+ @options = SilentMash.new(options)
33
33
 
34
34
  set_association_from_options
35
35
  join_special_params
@@ -48,7 +48,7 @@ module ZendeskAPI
48
48
 
49
49
  # Methods that take a Hash argument
50
50
  methods = %w{create find update update_many destroy}
51
- methods += methods.map {|method| method + "!"}
51
+ methods += methods.map { |method| method + "!" }
52
52
  methods.each do |deferrable|
53
53
  # Passes arguments and the proper path to the resource class method.
54
54
  # @param [Hash] options Options or attributes to pass
@@ -152,7 +152,7 @@ module ZendeskAPI
152
152
  # Adds an item (or items) to the list of side-loaded resources to request
153
153
  # @option sideloads [Symbol or String] The item(s) to sideload
154
154
  def include(*sideloads)
155
- self.tap { @includes.concat(sideloads.map(&:to_s)) }
155
+ tap { @includes.concat(sideloads.map(&:to_s)) }
156
156
  end
157
157
 
158
158
  # Adds an item to this collection
@@ -186,7 +186,7 @@ module ZendeskAPI
186
186
  return (@resources = [])
187
187
  end
188
188
 
189
- @response = get_response(@query || self.path)
189
+ @response = get_response(@query || path)
190
190
  handle_response(@response.body)
191
191
 
192
192
  @resources
@@ -194,7 +194,7 @@ module ZendeskAPI
194
194
 
195
195
  def fetch(*args)
196
196
  fetch!(*args)
197
- rescue Faraday::Error::ClientError => e
197
+ rescue Faraday::ClientError => e
198
198
  @error = e
199
199
 
200
200
  []
@@ -236,7 +236,7 @@ module ZendeskAPI
236
236
  # @option collection [Array] The collection to replace this one with
237
237
  # @raise [ArgumentError] if any resources passed in don't belong in this collection
238
238
  def replace(collection)
239
- raise "this collection is for #{@resource_class}" if collection.any?{|r| !r.is_a?(@resource_class) }
239
+ raise "this collection is for #{@resource_class}" if collection.any? { |r| !r.is_a?(@resource_class) }
240
240
  @resources = collection
241
241
  end
242
242
 
@@ -309,7 +309,7 @@ module ZendeskAPI
309
309
  inspect = []
310
310
  inspect << "options=#{@options.inspect}" if @options.any?
311
311
  inspect << "path=#{path}"
312
- "#{Inflection.singular(@resource)} collection [#{inspect.join(",")}]"
312
+ "#{Inflection.singular(@resource)} collection [#{inspect.join(',')}]"
313
313
  end
314
314
  end
315
315
 
@@ -398,7 +398,7 @@ module ZendeskAPI
398
398
  def get_response(path)
399
399
  @error = nil
400
400
  @response = @client.connection.send(@verb || "get", path) do |req|
401
- opts = @options.delete_if {|_, v| v.nil?}
401
+ opts = @options.delete_if { |_, v| v.nil? }
402
402
 
403
403
  req.params.merge!(:include => @includes.join(",")) if @includes.any?
404
404
 
@@ -16,6 +16,9 @@ module ZendeskAPI
16
16
  # @return [Boolean] Whether to attempt to retry when rate-limited (http status: 429).
17
17
  attr_accessor :retry
18
18
 
19
+ # @return [Boolean] Whether to raise error when rate-limited (http status: 429).
20
+ attr_accessor :raise_error_when_rate_limited
21
+
19
22
  # @return [Logger] Logger to use when logging requests.
20
23
  attr_accessor :logger
21
24
 
@@ -56,7 +59,8 @@ module ZendeskAPI
56
59
  :user_agent => "ZendeskAPI Ruby #{ZendeskAPI::VERSION}"
57
60
  },
58
61
  :request => {
59
- :open_timeout => 10
62
+ :open_timeout => 10,
63
+ :timeout => 60
60
64
  },
61
65
  :url => @url
62
66
  }.merge(client_options)
@@ -1,14 +1,23 @@
1
+ # tested via spec/core/middleware/response/raise_error_spec.rb
1
2
  module ZendeskAPI
2
3
  module Error
3
- class ClientError < Faraday::Error::ClientError
4
+ class ClientError < Faraday::ClientError
4
5
  attr_reader :wrapped_exception
6
+
7
+ def to_s
8
+ if response
9
+ "#{super} -- #{response.method} #{response.url}"
10
+ else
11
+ super
12
+ end
13
+ end
5
14
  end
6
15
 
7
16
  class RecordInvalid < ClientError
8
- attr_accessor :response, :errors
17
+ attr_accessor :errors
9
18
 
10
- def initialize(response)
11
- @response = response
19
+ def initialize(*)
20
+ super
12
21
 
13
22
  if response[:body].is_a?(Hash)
14
23
  @errors = response[:body]["details"] || response[:body]["description"]
@@ -18,11 +27,12 @@ module ZendeskAPI
18
27
  end
19
28
 
20
29
  def to_s
21
- "#{self.class.name}: #{@errors.to_s}"
30
+ "#{self.class.name}: #{@errors}"
22
31
  end
23
32
  end
24
33
 
25
34
  class NetworkError < ClientError; end
26
35
  class RecordNotFound < ClientError; end
36
+ class RateLimited < ClientError; end
27
37
  end
28
38
  end
@@ -3,18 +3,18 @@ module ZendeskAPI
3
3
  module Helpers
4
4
  # From https://github.com/rubyworks/facets/blob/master/lib/core/facets/string/modulize.rb
5
5
  def self.modulize_string(string)
6
- #gsub('__','/'). # why was this ever here?
7
- string.gsub(/__(.?)/){ "::#{$1.upcase}" }.
8
- gsub(/\/(.?)/){ "::#{$1.upcase}" }.
9
- gsub(/(?:_+|-+)([a-z])/){ $1.upcase }.
10
- gsub(/(\A|\s)([a-z])/){ $1 + $2.upcase }
6
+ # gsub('__','/'). # why was this ever here?
7
+ string.gsub(/__(.?)/) { "::#{$1.upcase}" }.
8
+ gsub(/\/(.?)/) { "::#{$1.upcase}" }.
9
+ gsub(/(?:_+|-+)([a-z])/) { $1.upcase }.
10
+ gsub(/(\A|\s)([a-z])/) { $1 + $2.upcase }
11
11
  end
12
12
 
13
13
  # From https://github.com/rubyworks/facets/blob/master/lib/core/facets/string/snakecase.rb
14
14
  def self.snakecase_string(string)
15
- #gsub(/::/, '/').
16
- string.gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
17
- gsub(/([a-z\d])([A-Z])/,'\1_\2').
15
+ # gsub(/::/, '/').
16
+ string.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2').
17
+ gsub(/([a-z\d])([A-Z])/, '\1_\2').
18
18
  tr('-', '_').
19
19
  gsub(/\s/, '_').
20
20
  gsub(/__+/, '_').
@@ -30,7 +30,11 @@ module ZendeskAPI
30
30
 
31
31
  @app.call(environment).on_complete do |env|
32
32
  if cached && env[:status] == 304 # not modified
33
+ # Handle differences in serialized env keys in Faraday < 1.0 and 1.0
34
+ # See https://github.com/lostisland/faraday/pull/847
33
35
  env[:body] = cached[:body]
36
+ env[:response_body] = cached[:response_body]
37
+
34
38
  env[:response_headers].merge!(
35
39
  :etag => cached[:response_headers][:etag],
36
40
  :content_type => cached[:response_headers][:content_type],
@@ -0,0 +1,31 @@
1
+ require 'faraday/middleware'
2
+ require 'zendesk_api/error'
3
+
4
+ module ZendeskAPI
5
+ module Middleware
6
+ # @private
7
+ module Request
8
+ # Faraday middleware to handle HTTP Status 429 (rate limiting) / 503 (maintenance)
9
+ # @private
10
+ class RaiseRateLimited < Faraday::Middleware
11
+ ERROR_CODES = [429, 503].freeze
12
+
13
+ def initialize(app, options = {})
14
+ super(app)
15
+ @logger = options[:logger]
16
+ end
17
+
18
+ def call(env)
19
+ response = @app.call(env)
20
+
21
+ if ERROR_CODES.include?(response.env[:status])
22
+ @logger&.warn 'You have been rate limited. Raising error...'
23
+ raise Error::RateLimited, env
24
+ else
25
+ response
26
+ end
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
@@ -10,7 +10,7 @@ module ZendeskAPI
10
10
  DEFAULT_RETRY_AFTER = 10
11
11
  ERROR_CODES = [429, 503]
12
12
 
13
- def initialize(app, options={})
13
+ def initialize(app, options = {})
14
14
  super(app)
15
15
  @logger = options[:logger]
16
16
  end
@@ -1,5 +1,5 @@
1
1
  require "faraday/middleware"
2
- require "mime/types"
2
+ require "mini_mime"
3
3
  require 'tempfile'
4
4
 
5
5
  module ZendeskAPI
@@ -50,7 +50,10 @@ module ZendeskAPI
50
50
  hash = hash[key]
51
51
  end
52
52
 
53
- mime_type ||= MIME::Types.type_for(path).first || "application/octet-stream"
53
+ unless defined?(mime_type) && !mime_type.nil?
54
+ mime_type = MiniMime.lookup_by_filename(path)
55
+ mime_type = mime_type ? mime_type.content_type : "application/octet-stream"
56
+ end
54
57
 
55
58
  hash[:filename] ||= if file.respond_to?(:original_filename)
56
59
  file.original_filename
@@ -12,7 +12,7 @@ module ZendeskAPI
12
12
 
13
13
  def call(env)
14
14
  @app.call(env).on_complete do |env|
15
- @client.callbacks.each {|c| c.call(env)}
15
+ @client.callbacks.each { |c| c.call(env) }
16
16
  end
17
17
  end
18
18
  end
@@ -4,6 +4,8 @@ module ZendeskAPI
4
4
  # Faraday middleware to handle logging
5
5
  # @private
6
6
  class Logger < Faraday::Middleware
7
+ LOG_LENGTH = 1000
8
+
7
9
  def initialize(app, logger = nil)
8
10
  super(app)
9
11
 
@@ -18,7 +20,10 @@ module ZendeskAPI
18
20
  @logger.debug dump_debug(env, :request_headers)
19
21
 
20
22
  @app.call(env).on_complete do |env|
21
- @logger.info("Status #{env[:status].to_s}")
23
+ info = "Status #{env[:status]}"
24
+ info.concat(" #{env[:body].to_s[0, LOG_LENGTH]}") if (400..499).cover?(env[:status].to_i)
25
+
26
+ @logger.info info
22
27
  @logger.debug dump_debug(env, :response_headers)
23
28
  end
24
29
  end
@@ -17,7 +17,7 @@ module ZendeskAPI
17
17
 
18
18
  def parse_dates!(value)
19
19
  case value
20
- when Hash then value.each { |key,element| value[key] = parse_dates!(element) }
20
+ when Hash then value.each { |key, element| value[key] = parse_dates!(element) }
21
21
  when Array then value.each_with_index { |element, index| value[index] = parse_dates!(element) }
22
22
  when /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z\Z/m then Time.parse(value)
23
23
  else