openapi_iplocation 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,78 @@
1
+ # OpenApiIplocationClient::DefaultApi
2
+
3
+ All URIs are relative to *https://api.iplocation.net*
4
+
5
+ | Method | HTTP request | Description |
6
+ | ------ | ------------ | ----------- |
7
+ | [**root_get**](DefaultApi.md#root_get) | **GET** / | Get geolocation of an IP address |
8
+
9
+
10
+ ## root_get
11
+
12
+ > <Get200Response> root_get(ip, opts)
13
+
14
+ Get geolocation of an IP address
15
+
16
+ Retrieve geolocation of an IP address.
17
+
18
+ ### Examples
19
+
20
+ ```ruby
21
+ require 'time'
22
+ require 'openapi_iplocation'
23
+
24
+ api_instance = OpenApiIplocationClient::DefaultApi.new
25
+ ip = 'ip_example' # String | An IPv4 or IPv6 address that you would like to lookup.
26
+ opts = {
27
+ format: 'format_example', # String | Output format, the following formats are supported: plain xml json jsonp php csv serialized
28
+ delimiter: 'delimiter_example' # String | Delimiter between proxies. Can be used only with format plain. The following types are supported: 1 for \"\\n\", 2 for \"<br>\".
29
+ }
30
+
31
+ begin
32
+ # Get geolocation of an IP address
33
+ result = api_instance.root_get(ip, opts)
34
+ p result
35
+ rescue OpenApiIplocationClient::ApiError => e
36
+ puts "Error when calling DefaultApi->root_get: #{e}"
37
+ end
38
+ ```
39
+
40
+ #### Using the root_get_with_http_info variant
41
+
42
+ This returns an Array which contains the response data, status code and headers.
43
+
44
+ > <Array(<Get200Response>, Integer, Hash)> root_get_with_http_info(ip, opts)
45
+
46
+ ```ruby
47
+ begin
48
+ # Get geolocation of an IP address
49
+ data, status_code, headers = api_instance.root_get_with_http_info(ip, opts)
50
+ p status_code # => 2xx
51
+ p headers # => { ... }
52
+ p data # => <Get200Response>
53
+ rescue OpenApiIplocationClient::ApiError => e
54
+ puts "Error when calling DefaultApi->root_get_with_http_info: #{e}"
55
+ end
56
+ ```
57
+
58
+ ### Parameters
59
+
60
+ | Name | Type | Description | Notes |
61
+ | ---- | ---- | ----------- | ----- |
62
+ | **ip** | **String** | An IPv4 or IPv6 address that you would like to lookup. | |
63
+ | **format** | **String** | Output format, the following formats are supported: plain xml json jsonp php csv serialized | [optional] |
64
+ | **delimiter** | **String** | Delimiter between proxies. Can be used only with format plain. The following types are supported: 1 for \&quot;\\n\&quot;, 2 for \&quot;&lt;br&gt;\&quot;. | [optional] |
65
+
66
+ ### Return type
67
+
68
+ [**Get200Response**](Get200Response.md)
69
+
70
+ ### Authorization
71
+
72
+ No authorization required
73
+
74
+ ### HTTP request headers
75
+
76
+ - **Content-Type**: Not defined
77
+ - **Accept**: application/json
78
+
@@ -0,0 +1,32 @@
1
+ # OpenApiIplocationClient::Get200Response
2
+
3
+ ## Properties
4
+
5
+ | Name | Type | Description | Notes |
6
+ | ---- | ---- | ----------- | ----- |
7
+ | **ip** | **String** | IPv4 or IPv6 address used to lookup geolocation. | [optional] |
8
+ | **ip_number** | **String** | IP number in long integer (represented as string). | [optional] |
9
+ | **ip_version** | **Integer** | IP version either 4 or 6. | [optional] |
10
+ | **country_name** | **String** | Full name of the IP country. | [optional] |
11
+ | **country_code2** | **String** | ISO ALPHA-2 Country Code. | [optional] |
12
+ | **isp** | **String** | Internet Service Provider (ISP) who owns the IP address. | [optional] |
13
+ | **response_code** | **String** | Response status code to indicate success or failed completion of the API call. | [optional] |
14
+ | **response_message** | **String** | Response message to indicate success or failed completion of the API call. | [optional] |
15
+
16
+ ## Example
17
+
18
+ ```ruby
19
+ require 'openapi_iplocation'
20
+
21
+ instance = OpenApiIplocationClient::Get200Response.new(
22
+ ip: null,
23
+ ip_number: null,
24
+ ip_version: null,
25
+ country_name: null,
26
+ country_code2: null,
27
+ isp: null,
28
+ response_code: null,
29
+ response_message: null
30
+ )
31
+ ```
32
+
@@ -0,0 +1,20 @@
1
+ # OpenApiIplocationClient::Get400Response
2
+
3
+ ## Properties
4
+
5
+ | Name | Type | Description | Notes |
6
+ | ---- | ---- | ----------- | ----- |
7
+ | **response_code** | **String** | Response status code to indicate success or failed completion of the API call. | [optional] |
8
+ | **response_message** | **String** | Response message to indicate success or failed completion of the API call. | [optional] |
9
+
10
+ ## Example
11
+
12
+ ```ruby
13
+ require 'openapi_iplocation'
14
+
15
+ instance = OpenApiIplocationClient::Get400Response.new(
16
+ response_code: null,
17
+ response_message: null
18
+ )
19
+ ```
20
+
data/git_push.sh ADDED
@@ -0,0 +1,57 @@
1
+ #!/bin/sh
2
+ # ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
3
+ #
4
+ # Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com"
5
+
6
+ git_user_id=$1
7
+ git_repo_id=$2
8
+ release_note=$3
9
+ git_host=$4
10
+
11
+ if [ "$git_host" = "" ]; then
12
+ git_host="github.com"
13
+ echo "[INFO] No command line input provided. Set \$git_host to $git_host"
14
+ fi
15
+
16
+ if [ "$git_user_id" = "" ]; then
17
+ git_user_id="GIT_USER_ID"
18
+ echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
19
+ fi
20
+
21
+ if [ "$git_repo_id" = "" ]; then
22
+ git_repo_id="GIT_REPO_ID"
23
+ echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
24
+ fi
25
+
26
+ if [ "$release_note" = "" ]; then
27
+ release_note="Minor update"
28
+ echo "[INFO] No command line input provided. Set \$release_note to $release_note"
29
+ fi
30
+
31
+ # Initialize the local directory as a Git repository
32
+ git init
33
+
34
+ # Adds the files in the local repository and stages them for commit.
35
+ git add .
36
+
37
+ # Commits the tracked changes and prepares them to be pushed to a remote repository.
38
+ git commit -m "$release_note"
39
+
40
+ # Sets the new remote
41
+ git_remote=$(git remote)
42
+ if [ "$git_remote" = "" ]; then # git remote not defined
43
+
44
+ if [ "$GIT_TOKEN" = "" ]; then
45
+ echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment."
46
+ git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git
47
+ else
48
+ git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git
49
+ fi
50
+
51
+ fi
52
+
53
+ git pull origin master
54
+
55
+ # Pushes (Forces) the changes in the local repository up to the remote repository
56
+ echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git"
57
+ git push origin master 2>&1 | grep -v 'To https'
@@ -0,0 +1,92 @@
1
+ =begin
2
+ #iplocation.net API
3
+
4
+ #OpenAPI v3 specification and a set of generated API clients for iplocation.net
5
+
6
+ The version of the OpenAPI document: 1.0.0
7
+ Contact: blah+oapicf@cliffano.com
8
+ Generated by: https://openapi-generator.tech
9
+ Generator version: 7.6.0
10
+
11
+ =end
12
+
13
+ require 'cgi'
14
+
15
+ module OpenApiIplocationClient
16
+ class DefaultApi
17
+ attr_accessor :api_client
18
+
19
+ def initialize(api_client = ApiClient.default)
20
+ @api_client = api_client
21
+ end
22
+ # Get geolocation of an IP address
23
+ # Retrieve geolocation of an IP address.
24
+ # @param ip [String] An IPv4 or IPv6 address that you would like to lookup.
25
+ # @param [Hash] opts the optional parameters
26
+ # @option opts [String] :format Output format, the following formats are supported: plain xml json jsonp php csv serialized
27
+ # @option opts [String] :delimiter Delimiter between proxies. Can be used only with format plain. The following types are supported: 1 for \&quot;\\n\&quot;, 2 for \&quot;&lt;br&gt;\&quot;.
28
+ # @return [Get200Response]
29
+ def root_get(ip, opts = {})
30
+ data, _status_code, _headers = root_get_with_http_info(ip, opts)
31
+ data
32
+ end
33
+
34
+ # Get geolocation of an IP address
35
+ # Retrieve geolocation of an IP address.
36
+ # @param ip [String] An IPv4 or IPv6 address that you would like to lookup.
37
+ # @param [Hash] opts the optional parameters
38
+ # @option opts [String] :format Output format, the following formats are supported: plain xml json jsonp php csv serialized
39
+ # @option opts [String] :delimiter Delimiter between proxies. Can be used only with format plain. The following types are supported: 1 for \&quot;\\n\&quot;, 2 for \&quot;&lt;br&gt;\&quot;.
40
+ # @return [Array<(Get200Response, Integer, Hash)>] Get200Response data, response status code and response headers
41
+ def root_get_with_http_info(ip, opts = {})
42
+ if @api_client.config.debugging
43
+ @api_client.config.logger.debug 'Calling API: DefaultApi.root_get ...'
44
+ end
45
+ # verify the required parameter 'ip' is set
46
+ if @api_client.config.client_side_validation && ip.nil?
47
+ fail ArgumentError, "Missing the required parameter 'ip' when calling DefaultApi.root_get"
48
+ end
49
+ # resource path
50
+ local_var_path = '/'
51
+
52
+ # query parameters
53
+ query_params = opts[:query_params] || {}
54
+ query_params[:'ip'] = ip
55
+ query_params[:'format'] = opts[:'format'] if !opts[:'format'].nil?
56
+ query_params[:'delimiter'] = opts[:'delimiter'] if !opts[:'delimiter'].nil?
57
+
58
+ # header parameters
59
+ header_params = opts[:header_params] || {}
60
+ # HTTP header 'Accept' (if needed)
61
+ header_params['Accept'] = @api_client.select_header_accept(['application/json'])
62
+
63
+ # form parameters
64
+ form_params = opts[:form_params] || {}
65
+
66
+ # http body (model)
67
+ post_body = opts[:debug_body]
68
+
69
+ # return_type
70
+ return_type = opts[:debug_return_type] || 'Get200Response'
71
+
72
+ # auth_names
73
+ auth_names = opts[:debug_auth_names] || []
74
+
75
+ new_options = opts.merge(
76
+ :operation => :"DefaultApi.root_get",
77
+ :header_params => header_params,
78
+ :query_params => query_params,
79
+ :form_params => form_params,
80
+ :body => post_body,
81
+ :auth_names => auth_names,
82
+ :return_type => return_type
83
+ )
84
+
85
+ data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)
86
+ if @api_client.config.debugging
87
+ @api_client.config.logger.debug "API called: DefaultApi#root_get\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
88
+ end
89
+ return data, status_code, headers
90
+ end
91
+ end
92
+ end
@@ -0,0 +1,393 @@
1
+ =begin
2
+ #iplocation.net API
3
+
4
+ #OpenAPI v3 specification and a set of generated API clients for iplocation.net
5
+
6
+ The version of the OpenAPI document: 1.0.0
7
+ Contact: blah+oapicf@cliffano.com
8
+ Generated by: https://openapi-generator.tech
9
+ Generator version: 7.6.0
10
+
11
+ =end
12
+
13
+ require 'date'
14
+ require 'json'
15
+ require 'logger'
16
+ require 'tempfile'
17
+ require 'time'
18
+ require 'typhoeus'
19
+
20
+
21
+ module OpenApiIplocationClient
22
+ class ApiClient
23
+ # The Configuration object holding settings to be used in the API client.
24
+ attr_accessor :config
25
+
26
+ # Defines the headers to be used in HTTP requests of all API calls by default.
27
+ #
28
+ # @return [Hash]
29
+ attr_accessor :default_headers
30
+
31
+ # Initializes the ApiClient
32
+ # @option config [Configuration] Configuration for initializing the object, default to Configuration.default
33
+ def initialize(config = Configuration.default)
34
+ @config = config
35
+ @user_agent = "OpenAPI-Generator/#{VERSION}/ruby"
36
+ @default_headers = {
37
+ 'Content-Type' => 'application/json',
38
+ 'User-Agent' => @user_agent
39
+ }
40
+ end
41
+
42
+ def self.default
43
+ @@default ||= ApiClient.new
44
+ end
45
+
46
+ # Call an API with given options.
47
+ #
48
+ # @return [Array<(Object, Integer, Hash)>] an array of 3 elements:
49
+ # the data deserialized from response body (may be a Tempfile or nil), response status code and response headers.
50
+ def call_api(http_method, path, opts = {})
51
+ request = build_request(http_method, path, opts)
52
+ tempfile = download_file(request) if opts[:return_type] == 'File'
53
+ response = request.run
54
+
55
+ if @config.debugging
56
+ @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
57
+ end
58
+
59
+ unless response.success?
60
+ if response.timed_out?
61
+ fail ApiError.new('Connection timed out')
62
+ elsif response.code == 0
63
+ # Errors from libcurl will be made visible here
64
+ fail ApiError.new(:code => 0,
65
+ :message => response.return_message)
66
+ else
67
+ fail ApiError.new(:code => response.code,
68
+ :response_headers => response.headers,
69
+ :response_body => response.body),
70
+ response.status_message
71
+ end
72
+ end
73
+
74
+ if opts[:return_type] == 'File'
75
+ data = tempfile
76
+ elsif opts[:return_type]
77
+ data = deserialize(response, opts[:return_type])
78
+ else
79
+ data = nil
80
+ end
81
+ return data, response.code, response.headers
82
+ end
83
+
84
+ # Builds the HTTP request
85
+ #
86
+ # @param [String] http_method HTTP method/verb (e.g. POST)
87
+ # @param [String] path URL path (e.g. /account/new)
88
+ # @option opts [Hash] :header_params Header parameters
89
+ # @option opts [Hash] :query_params Query parameters
90
+ # @option opts [Hash] :form_params Query parameters
91
+ # @option opts [Object] :body HTTP body (JSON/XML)
92
+ # @return [Typhoeus::Request] A Typhoeus Request
93
+ def build_request(http_method, path, opts = {})
94
+ url = build_request_url(path, opts)
95
+ http_method = http_method.to_sym.downcase
96
+
97
+ header_params = @default_headers.merge(opts[:header_params] || {})
98
+ query_params = opts[:query_params] || {}
99
+ form_params = opts[:form_params] || {}
100
+ follow_location = opts[:follow_location] || true
101
+
102
+
103
+ # set ssl_verifyhosts option based on @config.verify_ssl_host (true/false)
104
+ _verify_ssl_host = @config.verify_ssl_host ? 2 : 0
105
+
106
+ req_opts = {
107
+ :method => http_method,
108
+ :headers => header_params,
109
+ :params => query_params,
110
+ :params_encoding => @config.params_encoding,
111
+ :timeout => @config.timeout,
112
+ :ssl_verifypeer => @config.verify_ssl,
113
+ :ssl_verifyhost => _verify_ssl_host,
114
+ :sslcert => @config.cert_file,
115
+ :sslkey => @config.key_file,
116
+ :verbose => @config.debugging,
117
+ :followlocation => follow_location
118
+ }
119
+
120
+ # set custom cert, if provided
121
+ req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert
122
+
123
+ if [:post, :patch, :put, :delete].include?(http_method)
124
+ req_body = build_request_body(header_params, form_params, opts[:body])
125
+ req_opts.update :body => req_body
126
+ if @config.debugging
127
+ @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
128
+ end
129
+ end
130
+
131
+ Typhoeus::Request.new(url, req_opts)
132
+ end
133
+
134
+ # Builds the HTTP request body
135
+ #
136
+ # @param [Hash] header_params Header parameters
137
+ # @param [Hash] form_params Query parameters
138
+ # @param [Object] body HTTP body (JSON/XML)
139
+ # @return [String] HTTP body data in the form of string
140
+ def build_request_body(header_params, form_params, body)
141
+ # http form
142
+ if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
143
+ header_params['Content-Type'] == 'multipart/form-data'
144
+ data = {}
145
+ form_params.each do |key, value|
146
+ case value
147
+ when ::File, ::Array, nil
148
+ # let typhoeus handle File, Array and nil parameters
149
+ data[key] = value
150
+ else
151
+ data[key] = value.to_s
152
+ end
153
+ end
154
+ elsif body
155
+ data = body.is_a?(String) ? body : body.to_json
156
+ else
157
+ data = nil
158
+ end
159
+ data
160
+ end
161
+
162
+ # Save response body into a file in (the defined) temporary folder, using the filename
163
+ # from the "Content-Disposition" header if provided, otherwise a random filename.
164
+ # The response body is written to the file in chunks in order to handle files which
165
+ # size is larger than maximum Ruby String or even larger than the maximum memory a Ruby
166
+ # process can use.
167
+ #
168
+ # @see Configuration#temp_folder_path
169
+ #
170
+ # @return [Tempfile] the tempfile generated
171
+ def download_file(request)
172
+ tempfile = nil
173
+ encoding = nil
174
+ request.on_headers do |response|
175
+ content_disposition = response.headers['Content-Disposition']
176
+ if content_disposition && content_disposition =~ /filename=/i
177
+ filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
178
+ prefix = sanitize_filename(filename)
179
+ else
180
+ prefix = 'download-'
181
+ end
182
+ prefix = prefix + '-' unless prefix.end_with?('-')
183
+ encoding = response.body.encoding
184
+ tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
185
+ end
186
+ request.on_body do |chunk|
187
+ chunk.force_encoding(encoding)
188
+ tempfile.write(chunk)
189
+ end
190
+ # run the request to ensure the tempfile is created successfully before returning it
191
+ request.run
192
+ if tempfile
193
+ tempfile.close
194
+ @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\
195
+ "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
196
+ "will be deleted automatically with GC. It's also recommended to delete the temp file "\
197
+ "explicitly with `tempfile.delete`"
198
+ else
199
+ fail ApiError.new("Failed to create the tempfile based on the HTTP response from the server: #{request.inspect}")
200
+ end
201
+
202
+ tempfile
203
+ end
204
+
205
+ # Check if the given MIME is a JSON MIME.
206
+ # JSON MIME examples:
207
+ # application/json
208
+ # application/json; charset=UTF8
209
+ # APPLICATION/JSON
210
+ # */*
211
+ # @param [String] mime MIME
212
+ # @return [Boolean] True if the MIME is application/json
213
+ def json_mime?(mime)
214
+ (mime == '*/*') || !(mime =~ /^Application\/.*json(?!p)(;.*)?/i).nil?
215
+ end
216
+
217
+ # Deserialize the response to the given return type.
218
+ #
219
+ # @param [Response] response HTTP response
220
+ # @param [String] return_type some examples: "User", "Array<User>", "Hash<String, Integer>"
221
+ def deserialize(response, return_type)
222
+ body = response.body
223
+ return nil if body.nil? || body.empty?
224
+
225
+ # return response body directly for String return type
226
+ return body.to_s if return_type == 'String'
227
+
228
+ # ensuring a default content type
229
+ content_type = response.headers['Content-Type'] || 'application/json'
230
+
231
+ fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
232
+
233
+ begin
234
+ data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
235
+ rescue JSON::ParserError => e
236
+ if %w(String Date Time).include?(return_type)
237
+ data = body
238
+ else
239
+ raise e
240
+ end
241
+ end
242
+
243
+ convert_to_type data, return_type
244
+ end
245
+
246
+ # Convert data to the given return type.
247
+ # @param [Object] data Data to be converted
248
+ # @param [String] return_type Return type
249
+ # @return [Mixed] Data in a particular type
250
+ def convert_to_type(data, return_type)
251
+ return nil if data.nil?
252
+ case return_type
253
+ when 'String'
254
+ data.to_s
255
+ when 'Integer'
256
+ data.to_i
257
+ when 'Float'
258
+ data.to_f
259
+ when 'Boolean'
260
+ data == true
261
+ when 'Time'
262
+ # parse date time (expecting ISO 8601 format)
263
+ Time.parse data
264
+ when 'Date'
265
+ # parse date time (expecting ISO 8601 format)
266
+ Date.parse data
267
+ when 'Object'
268
+ # generic object (usually a Hash), return directly
269
+ data
270
+ when /\AArray<(.+)>\z/
271
+ # e.g. Array<Pet>
272
+ sub_type = $1
273
+ data.map { |item| convert_to_type(item, sub_type) }
274
+ when /\AHash\<String, (.+)\>\z/
275
+ # e.g. Hash<String, Integer>
276
+ sub_type = $1
277
+ {}.tap do |hash|
278
+ data.each { |k, v| hash[k] = convert_to_type(v, sub_type) }
279
+ end
280
+ else
281
+ # models (e.g. Pet) or oneOf
282
+ klass = OpenApiIplocationClient.const_get(return_type)
283
+ klass.respond_to?(:openapi_one_of) ? klass.build(data) : klass.build_from_hash(data)
284
+ end
285
+ end
286
+
287
+ # Sanitize filename by removing path.
288
+ # e.g. ../../sun.gif becomes sun.gif
289
+ #
290
+ # @param [String] filename the filename to be sanitized
291
+ # @return [String] the sanitized filename
292
+ def sanitize_filename(filename)
293
+ filename.split(/[\/\\]/).last
294
+ end
295
+
296
+ def build_request_url(path, opts = {})
297
+ # Add leading and trailing slashes to path
298
+ path = "/#{path}".gsub(/\/+/, '/')
299
+ @config.base_url(opts[:operation]) + path
300
+ end
301
+
302
+ # Update header and query params based on authentication settings.
303
+ #
304
+ # @param [Hash] header_params Header parameters
305
+ # @param [Hash] query_params Query parameters
306
+ # @param [String] auth_names Authentication scheme name
307
+ def update_params_for_auth!(header_params, query_params, auth_names)
308
+ Array(auth_names).each do |auth_name|
309
+ auth_setting = @config.auth_settings[auth_name]
310
+ next unless auth_setting
311
+ case auth_setting[:in]
312
+ when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
313
+ when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
314
+ else fail ArgumentError, 'Authentication token must be in `query` or `header`'
315
+ end
316
+ end
317
+ end
318
+
319
+ # Sets user agent in HTTP header
320
+ #
321
+ # @param [String] user_agent User agent (e.g. openapi-generator/ruby/1.0.0)
322
+ def user_agent=(user_agent)
323
+ @user_agent = user_agent
324
+ @default_headers['User-Agent'] = @user_agent
325
+ end
326
+
327
+ # Return Accept header based on an array of accepts provided.
328
+ # @param [Array] accepts array for Accept
329
+ # @return [String] the Accept header (e.g. application/json)
330
+ def select_header_accept(accepts)
331
+ return nil if accepts.nil? || accepts.empty?
332
+ # use JSON when present, otherwise use all of the provided
333
+ json_accept = accepts.find { |s| json_mime?(s) }
334
+ json_accept || accepts.join(',')
335
+ end
336
+
337
+ # Return Content-Type header based on an array of content types provided.
338
+ # @param [Array] content_types array for Content-Type
339
+ # @return [String] the Content-Type header (e.g. application/json)
340
+ def select_header_content_type(content_types)
341
+ # return nil by default
342
+ return if content_types.nil? || content_types.empty?
343
+ # use JSON when present, otherwise use the first one
344
+ json_content_type = content_types.find { |s| json_mime?(s) }
345
+ json_content_type || content_types.first
346
+ end
347
+
348
+ # Convert object (array, hash, object, etc) to JSON string.
349
+ # @param [Object] model object to be converted into JSON string
350
+ # @return [String] JSON string representation of the object
351
+ def object_to_http_body(model)
352
+ return model if model.nil? || model.is_a?(String)
353
+ local_body = nil
354
+ if model.is_a?(Array)
355
+ local_body = model.map { |m| object_to_hash(m) }
356
+ else
357
+ local_body = object_to_hash(model)
358
+ end
359
+ local_body.to_json
360
+ end
361
+
362
+ # Convert object(non-array) to hash.
363
+ # @param [Object] obj object to be converted into JSON string
364
+ # @return [String] JSON string representation of the object
365
+ def object_to_hash(obj)
366
+ if obj.respond_to?(:to_hash)
367
+ obj.to_hash
368
+ else
369
+ obj
370
+ end
371
+ end
372
+
373
+ # Build parameter value according to the given collection format.
374
+ # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
375
+ def build_collection_param(param, collection_format)
376
+ case collection_format
377
+ when :csv
378
+ param.join(',')
379
+ when :ssv
380
+ param.join(' ')
381
+ when :tsv
382
+ param.join("\t")
383
+ when :pipes
384
+ param.join('|')
385
+ when :multi
386
+ # return the array directly as typhoeus will handle it as expected
387
+ param
388
+ else
389
+ fail "unknown collection format: #{collection_format.inspect}"
390
+ end
391
+ end
392
+ end
393
+ end