weather_API_Assignment 1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (30) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +28 -0
  3. data/README.md +187 -0
  4. data/lib/weather_api_assignment.rb +46 -0
  5. data/lib/weather_api_assignment/api_helper.rb +275 -0
  6. data/lib/weather_api_assignment/configuration.rb +24 -0
  7. data/lib/weather_api_assignment/controllers/base_controller.rb +51 -0
  8. data/lib/weather_api_assignment/controllers/weather_ap_is_controller.rb +121 -0
  9. data/lib/weather_api_assignment/exceptions/api_exception.rb +20 -0
  10. data/lib/weather_api_assignment/http/auth/custom_query_auth.rb +16 -0
  11. data/lib/weather_api_assignment/http/faraday_client.rb +64 -0
  12. data/lib/weather_api_assignment/http/http_call_back.rb +24 -0
  13. data/lib/weather_api_assignment/http/http_client.rb +104 -0
  14. data/lib/weather_api_assignment/http/http_context.rb +20 -0
  15. data/lib/weather_api_assignment/http/http_method_enum.rb +13 -0
  16. data/lib/weather_api_assignment/http/http_request.rb +50 -0
  17. data/lib/weather_api_assignment/http/http_response.rb +23 -0
  18. data/lib/weather_api_assignment/models/base_model.rb +36 -0
  19. data/lib/weather_api_assignment/models/clouds.rb +35 -0
  20. data/lib/weather_api_assignment/models/coord.rb +44 -0
  21. data/lib/weather_api_assignment/models/lang_enum.rb +20 -0
  22. data/lib/weather_api_assignment/models/main.rb +98 -0
  23. data/lib/weather_api_assignment/models/mode_enum.rb +20 -0
  24. data/lib/weather_api_assignment/models/sys.rb +80 -0
  25. data/lib/weather_api_assignment/models/units_enum.rb +20 -0
  26. data/lib/weather_api_assignment/models/weather.rb +62 -0
  27. data/lib/weather_api_assignment/models/weather_api_response.rb +150 -0
  28. data/lib/weather_api_assignment/models/wind.rb +44 -0
  29. data/lib/weather_api_assignment/weather_api_assignment_client.rb +27 -0
  30. metadata +167 -0
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 333073786678d1c376cb0027ba05c8c39da196572fd6ca56f5ea546f154c4271
4
+ data.tar.gz: e9569587183412572dbbcb09ab6e97c7b03be4ea2bf009d34e8fb59dfc35df74
5
+ SHA512:
6
+ metadata.gz: 9dbdfe3032c4e79dd40a0dbe395de5cd42a48b9436b7c0e609260f7abf6f927231d545f05e48c2ba3277d0328ff1621a1d3b07c9bad3396b559594a0c654c2bd
7
+ data.tar.gz: 48a62ff715e67df4fed53ead69d385f5adb8444c874fbd5d3bac07c5f75ba81062ed6b6073960c651a0beb3b8ec569bbf473eccf02c0f2d36c9af93c4593850d
data/LICENSE ADDED
@@ -0,0 +1,28 @@
1
+ License:
2
+ ========
3
+ The MIT License (MIT)
4
+ http://opensource.org/licenses/MIT
5
+
6
+ Copyright (c) 2014 - 2016 APIMATIC Limited
7
+
8
+ Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ of this software and associated documentation files (the "Software"), to deal
10
+ in the Software without restriction, including without limitation the rights
11
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ copies of the Software, and to permit persons to whom the Software is
13
+ furnished to do so, subject to the following conditions:
14
+
15
+ The above copyright notice and this permission notice shall be included in
16
+ all copies or substantial portions of the Software.
17
+
18
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24
+ THE SOFTWARE.
25
+
26
+ Trade Mark:
27
+ ==========
28
+ APIMATIC is a trade mark for APIMATIC Limited
@@ -0,0 +1,187 @@
1
+ # Getting started
2
+
3
+ This API will provide latest information of current weather
4
+
5
+ ## How to Build
6
+
7
+ This client library is a Ruby gem which can be compiled and used in your Ruby and Ruby on Rails project. This library requires a few gems from the RubyGems repository.
8
+
9
+ 1. Open the command line interface or the terminal and navigate to the folder containing the source code.
10
+ 2. Run ``` gem build weather_api_assignment.gemspec ``` to build the gem.
11
+ 3. Once built, the gem can be installed on the current work environment using ``` gem install weather_api_assignment-1.0.gem ```
12
+
13
+ ![Building Gem](https://apidocs.io/illustration/ruby?step=buildSDK&workspaceFolder=Weather_API-Ruby&workspaceName=Weather_API-Ruby&projectName=weather_api_assignment&gemName=weather_api_assignment&gemVer=1.0)
14
+
15
+ ## How to Use
16
+
17
+ The following section explains how to use the WeatherApiAssignment Ruby Gem in a new Rails project using RubyMine™. The basic workflow presented here is also applicable if you prefer using a different editor or IDE.
18
+
19
+ ### 1. Starting a new project
20
+
21
+ Close any existing projects in RubyMine™ by selecting ``` File -> Close Project ```. Next, click on ``` Create New Project ``` to create a new project from scratch.
22
+
23
+ ![Create a new project in RubyMine](https://apidocs.io/illustration/ruby?step=createNewProject0&workspaceFolder=Weather_API-Ruby&workspaceName=WeatherApiAssignment&projectName=weather_api_assignment&gemName=weather_api_assignment&gemVer=1.0)
24
+
25
+ Next, provide ``` TestApp ``` as the project name, choose ``` Rails Application ``` as the project type, and click ``` OK ```.
26
+
27
+ ![Create a new Rails Application in RubyMine - step 1](https://apidocs.io/illustration/ruby?step=createNewProject1&workspaceFolder=Weather_API-Ruby&workspaceName=WeatherApiAssignment&projectName=weather_api_assignment&gemName=weather_api_assignment&gemVer=1.0)
28
+
29
+ In the next dialog make sure that correct *Ruby SDK* is being used (minimum 2.0.0) and click ``` OK ```.
30
+
31
+ ![Create a new Rails Application in RubyMine - step 2](https://apidocs.io/illustration/ruby?step=createNewProject2&workspaceFolder=Weather_API-Ruby&workspaceName=WeatherApiAssignment&projectName=weather_api_assignment&gemName=weather_api_assignment&gemVer=1.0)
32
+
33
+ This will create a new Rails Application project with an existing set of files and folder.
34
+
35
+ ### 2. Add reference of the gem
36
+
37
+ In order to use the WeatherApiAssignment gem in the new project we must add a gem reference. Locate the ```Gemfile``` in the *Project Explorer* window under the ``` TestApp ``` project node. The file contains references to all gems being used in the project. Here, add the reference to the library gem by adding the following line: ``` gem 'weather_api_assignment', '~> 1.0' ```
38
+
39
+ ![Add references of the Gemfile](https://apidocs.io/illustration/ruby?step=addReference&workspaceFolder=Weather_API-Ruby&workspaceName=WeatherApiAssignment&projectName=weather_api_assignment&gemName=weather_api_assignment&gemVer=1.0)
40
+
41
+ ### 3. Adding a new Rails Controller
42
+
43
+ Once the ``` TestApp ``` project is created, a folder named ``` controllers ``` will be visible in the *Project Explorer* under the following path: ``` TestApp > app > controllers ```. Right click on this folder and select ``` New -> Run Rails Generator... ```.
44
+
45
+ ![Run Rails Generator on Controllers Folder](https://apidocs.io/illustration/ruby?step=addCode0&workspaceFolder=Weather_API-Ruby&workspaceName=WeatherApiAssignment&projectName=weather_api_assignment&gemName=weather_api_assignment&gemVer=1.0)
46
+
47
+ Selecting the said option will popup a small window where the generator names are displayed. Here, select the ``` controller ``` template.
48
+
49
+ ![Create a new Controller](https://apidocs.io/illustration/ruby?step=addCode1&workspaceFolder=Weather_API-Ruby&workspaceName=WeatherApiAssignment&projectName=weather_api_assignment&gemName=weather_api_assignment&gemVer=1.0)
50
+
51
+ Next, a popup window will ask you for a Controller name and included Actions. For controller name provide ``` Hello ``` and include an action named ``` Index ``` and click ``` OK ```.
52
+
53
+ ![Add a new Controller](https://apidocs.io/illustration/ruby?step=addCode2&workspaceFolder=Weather_API-Ruby&workspaceName=WeatherApiAssignment&projectName=weather_api_assignment&gemName=weather_api_assignment&gemVer=1.0)
54
+
55
+ A new controller class anmed ``` HelloController ``` will be created in a file named ``` hello_controller.rb ``` containing a method named ``` Index ```. In this method, add code for initialization and a sample for its usage.
56
+
57
+ ![Initialize the library](https://apidocs.io/illustration/ruby?step=addCode3&workspaceFolder=Weather_API-Ruby&workspaceName=WeatherApiAssignment&projectName=weather_api_assignment&gemName=weather_api_assignment&gemVer=1.0)
58
+
59
+ ## How to Test
60
+
61
+ You can test the generated SDK and the server with automatically generated test
62
+ cases as follows:
63
+
64
+ 1. From terminal/cmd navigate to the root directory of the SDK.
65
+ 2. Invoke: `bundle exec rake`
66
+
67
+ ## Initialization
68
+
69
+ ### Authentication
70
+ In order to setup authentication and initialization of the API client, you need the following information.
71
+
72
+ | Parameter | Description |
73
+ |-----------|-------------|
74
+ | appid | App key for authentication |
75
+
76
+
77
+
78
+ API client can be initialized as following.
79
+
80
+ ```ruby
81
+ # Configuration parameters and credentials
82
+ appid = '178db63aed00f6e4daaa06009b04438b' # App key for authentication
83
+
84
+ client = WeatherApiAssignment::WeatherApiAssignmentClient.new(
85
+ appid: appid
86
+ )
87
+ ```
88
+
89
+ The added initlization code can be debugged by putting a breakpoint in the ``` Index ``` method and running the project in debug mode by selecting ``` Run -> Debug 'Development: TestApp' ```.
90
+
91
+ ![Debug the TestApp](https://apidocs.io/illustration/ruby?step=addCode4&workspaceFolder=Weather_API-Ruby&workspaceName=WeatherApiAssignment&projectName=weather_api_assignment&gemName=weather_api_assignment&gemVer=1.0&initLine=client%2520%253D%2520WeatherApiAssignmentClient.new%2528%2527appid%2527%2529)
92
+
93
+
94
+
95
+ # Class Reference
96
+
97
+ ## <a name="list_of_controllers"></a>List of Controllers
98
+
99
+ * [WeatherAPIsController](#weather_ap_is_controller)
100
+
101
+ ## <a name="weather_ap_is_controller"></a>![Class: ](https://apidocs.io/img/class.png ".WeatherAPIsController") WeatherAPIsController
102
+
103
+ ### Get singleton instance
104
+
105
+ The singleton instance of the ``` WeatherAPIsController ``` class can be accessed from the API Client.
106
+
107
+ ```ruby
108
+ weatherAPIs_controller = client.weather_ap_is
109
+ ```
110
+
111
+ ### <a name="get_weather_by_city_name"></a>![Method: ](https://apidocs.io/img/method.png ".WeatherAPIsController.get_weather_by_city_name") get_weather_by_city_name
112
+
113
+ > This is a weather API endpoint which returns the current weather of a location by city name.
114
+
115
+
116
+ ```ruby
117
+ def get_weather_by_city_name(q,
118
+ mode = nil,
119
+ units = nil,
120
+ lang = nil); end
121
+ ```
122
+
123
+ #### Parameters
124
+
125
+ | Parameter | Tags | Description |
126
+ |-----------|------|-------------|
127
+ | q | ``` Required ``` ``` DefaultValue ``` | City name, state code and country code divided by comma, use ISO 3166 country codes. |
128
+ | mode | ``` Optional ``` | Response format. Possible values are xml and html. If you don't use the mode parameter format is JSON by default. |
129
+ | units | ``` Optional ``` | Units of measurement. standard, metric and imperial units are available. If you do not use the units parameter, standard units will be applied by default. |
130
+ | lang | ``` Optional ``` | You can use this parameter to get the output in your language. |
131
+
132
+
133
+ #### Example Usage
134
+
135
+ ```ruby
136
+ q = 'London,uk'
137
+ mode = WeatherApiAssignment::MODEEnum::XML
138
+ units = WeatherApiAssignment::UNITSEnum::STANDARD
139
+ lang = WeatherApiAssignment::LANGEnum::AF
140
+
141
+ result = weatherAPIs_controller.get_weather_by_city_name(q, mode, units, lang)
142
+
143
+ ```
144
+
145
+
146
+ ### <a name="get_weather_by_latitude_and_longitude"></a>![Method: ](https://apidocs.io/img/method.png ".WeatherAPIsController.get_weather_by_latitude_and_longitude") get_weather_by_latitude_and_longitude
147
+
148
+ > This is a weather API endpoint which returns the current weather of a location by latitude and longitude.
149
+
150
+
151
+ ```ruby
152
+ def get_weather_by_latitude_and_longitude(lat,
153
+ lon,
154
+ mode = nil,
155
+ units = nil,
156
+ lang = nil); end
157
+ ```
158
+
159
+ #### Parameters
160
+
161
+ | Parameter | Tags | Description |
162
+ |-----------|------|-------------|
163
+ | lat | ``` Required ``` | This field will contain the latitude of city |
164
+ | lon | ``` Required ``` | This field will contain the longitude of city |
165
+ | mode | ``` Optional ``` | Response format. Possible values are xml and html. If you don't use the mode parameter format is JSON by default. |
166
+ | units | ``` Optional ``` | Units of measurement. standard, metric and imperial units are available. If you do not use the units parameter, standard units will be applied by default. |
167
+ | lang | ``` Optional ``` | You can use this parameter to get the output in your language. |
168
+
169
+
170
+ #### Example Usage
171
+
172
+ ```ruby
173
+ lat = 29.0834359890239
174
+ lon = 29.0834359890239
175
+ mode = WeatherApiAssignment::MODEEnum::XML
176
+ units = WeatherApiAssignment::UNITSEnum::STANDARD
177
+ lang = 'lang'
178
+
179
+ result = weatherAPIs_controller.get_weather_by_latitude_and_longitude(lat, lon, mode, units, lang)
180
+
181
+ ```
182
+
183
+
184
+ [Back to List of Controllers](#list_of_controllers)
185
+
186
+
187
+
@@ -0,0 +1,46 @@
1
+ # weather_api_assignment
2
+ #
3
+ # This file was automatically generated by APIMATIC
4
+ # v2.0 ( https://apimatic.io ).
5
+
6
+ require 'date'
7
+ require 'json'
8
+ require 'faraday'
9
+ require 'certifi'
10
+ require 'logging'
11
+
12
+ require_relative 'weather_api_assignment/api_helper.rb'
13
+ require_relative 'weather_api_assignment/weather_api_assignment_client.rb'
14
+
15
+ # Http
16
+ require_relative 'weather_api_assignment/http/http_call_back.rb'
17
+ require_relative 'weather_api_assignment/http/http_client.rb'
18
+ require_relative 'weather_api_assignment/http/http_method_enum.rb'
19
+ require_relative 'weather_api_assignment/http/http_request.rb'
20
+ require_relative 'weather_api_assignment/http/http_response.rb'
21
+ require_relative 'weather_api_assignment/http/http_context.rb'
22
+ require_relative 'weather_api_assignment/http/faraday_client.rb'
23
+ require_relative 'weather_api_assignment/http/auth/custom_query_auth.rb'
24
+
25
+ # Models
26
+ require_relative 'weather_api_assignment/models/base_model.rb'
27
+ require_relative 'weather_api_assignment/models/weather_api_response.rb'
28
+ require_relative 'weather_api_assignment/models/coord.rb'
29
+ require_relative 'weather_api_assignment/models/weather.rb'
30
+ require_relative 'weather_api_assignment/models/main.rb'
31
+ require_relative 'weather_api_assignment/models/wind.rb'
32
+ require_relative 'weather_api_assignment/models/clouds.rb'
33
+ require_relative 'weather_api_assignment/models/sys.rb'
34
+ require_relative 'weather_api_assignment/models/mode_enum.rb'
35
+ require_relative 'weather_api_assignment/models/units_enum.rb'
36
+ require_relative 'weather_api_assignment/models/lang_enum.rb'
37
+
38
+ # Exceptions
39
+ require_relative 'weather_api_assignment/exceptions/api_exception.rb'
40
+
41
+ require_relative 'weather_api_assignment/configuration.rb'
42
+
43
+ # Controllers
44
+ require_relative 'weather_api_assignment/controllers/base_controller.rb'
45
+ require_relative 'weather_api_assignment/controllers/weather_ap_is' \
46
+ '_controller.rb'
@@ -0,0 +1,275 @@
1
+ # weather_api_assignment
2
+ #
3
+ # This file was automatically generated by APIMATIC
4
+ # v2.0 ( https://apimatic.io ).
5
+
6
+ module WeatherApiAssignment
7
+ # API utility class
8
+ class APIHelper
9
+ # Serializes an array parameter (creates key value pairs).
10
+ # @param [String] The name of the parameter.
11
+ # @param [Array] The value of the parameter.
12
+ # @param [String] The format of the serialization.
13
+ def self.serialize_array(key, array, formatting: 'indexed')
14
+ tuples = []
15
+
16
+ if formatting == 'unindexed'
17
+ tuples += array.map { |element| ["#{key}[]", element] }
18
+ elsif formatting == 'indexed'
19
+ tuples += array.map.with_index do |element, index|
20
+ ["#{key}[#{index}]", element]
21
+ end
22
+ elsif formatting == 'plain'
23
+ tuples += array.map { |element| [key, element] }
24
+ else
25
+ raise ArgumentError, 'Invalid format provided.'
26
+ end
27
+ tuples
28
+ end
29
+
30
+ # Replaces template parameters in the given url.
31
+ # @param [String] The query string builder to replace the template
32
+ # parameters.
33
+ # @param [Hash] The parameters to replace in the url.
34
+ def self.append_url_with_template_parameters(query_builder, parameters)
35
+ # perform parameter validation
36
+ unless query_builder.instance_of? String
37
+ raise ArgumentError, 'Given value for parameter \"query_builder\" is
38
+ invalid.'
39
+ end
40
+
41
+ # Return if there are no parameters to replace.
42
+ return query_builder if parameters.nil?
43
+
44
+ # Iterate and append parameters.
45
+ parameters.each do |key, value|
46
+ replace_value = ''
47
+
48
+ if value.nil?
49
+ replace_value = ''
50
+ elsif value.instance_of? Array
51
+ value.map! { |element| CGI.escape(element.to_s) }
52
+ replace_value = value.join('/')
53
+ else
54
+ replace_value = CGI.escape(value.to_s)
55
+ end
56
+
57
+ # Find the template parameter and replace it with its value.
58
+ query_builder = query_builder.gsub('{' + key.to_s + '}', replace_value)
59
+ end
60
+ query_builder
61
+ end
62
+
63
+ # Appends the given set of parameters to the given query string.
64
+ # @param [String] The query string builder to add the query parameters to.
65
+ # @param [Hash] The parameters to append.
66
+ # @param [String] The format of array parameter serialization.
67
+ def self.append_url_with_query_parameters(query_builder, parameters,
68
+ array_serialization: 'indexed')
69
+ # Perform parameter validation.
70
+ unless query_builder.instance_of? String
71
+ raise ArgumentError, 'Given value for parameter \"query_builder\"
72
+ is invalid.'
73
+ end
74
+
75
+ # Return if there are no parameters to replace.
76
+ return query_builder if parameters.nil?
77
+
78
+ parameters.each do |key, value|
79
+ seperator = query_builder.include?('?') ? '&' : '?'
80
+ unless value.nil?
81
+ if value.instance_of? Array
82
+ value.compact!
83
+ query_builder += if array_serialization == 'csv'
84
+ "#{seperator}#{key}=#{value.map do |element|
85
+ CGI.escape(element.to_s)
86
+ end.join(',')}"
87
+ elsif array_serialization == 'psv'
88
+ "#{seperator}#{key}=#{value.map do |element|
89
+ CGI.escape(element.to_s)
90
+ end.join('|')}"
91
+ elsif array_serialization == 'tsv'
92
+ "#{seperator}#{key}=#{value.map do |element|
93
+ CGI.escape(element.to_s)
94
+ end.join("\t")}"
95
+ else
96
+ "#{seperator}#{APIHelper.serialize_array(
97
+ key, value, formatting: array_serialization
98
+ ).map { |k, v| "#{k}=#{CGI.escape(v.to_s)}" }
99
+ .join('&')}"
100
+ end
101
+ else
102
+ query_builder += "#{seperator}#{key}=#{CGI.escape(value.to_s)}"
103
+ end
104
+ end
105
+ end
106
+ query_builder
107
+ end
108
+
109
+ # Validates and processes the given Url.
110
+ # @param [String] The given Url to process.
111
+ # @return [String] Pre-processed Url as string.
112
+ def self.clean_url(url)
113
+ # Perform parameter validation.
114
+ raise ArgumentError, 'Invalid Url.' unless url.instance_of? String
115
+
116
+ # Ensure that the urls are absolute.
117
+ matches = url.match(%r{^(https?:\/\/[^\/]+)})
118
+ raise ArgumentError, 'Invalid Url format.' if matches.nil?
119
+
120
+ # Get the http protocol match.
121
+ protocol = matches[1]
122
+
123
+ # Check if parameters exist.
124
+ index = url.index('?')
125
+
126
+ # Remove redundant forward slashes.
127
+ query = url[protocol.length...(!index.nil? ? index : url.length)]
128
+ query.gsub!(%r{\/\/+}, '/')
129
+
130
+ # Get the parameters.
131
+ parameters = !index.nil? ? url[url.index('?')...url.length] : ''
132
+
133
+ # Return processed url.
134
+ protocol + query + parameters
135
+ end
136
+
137
+ # Parses JSON string.
138
+ # @param [String] A JSON string.
139
+ def self.json_deserialize(json)
140
+ return JSON.parse(json)
141
+ rescue StandardError
142
+ raise TypeError, 'Server responded with invalid JSON.'
143
+ end
144
+
145
+ # Removes elements with empty values from a hash.
146
+ # @param [Hash] The hash to clean.
147
+ def self.clean_hash(hash)
148
+ hash.delete_if { |_key, value| value.to_s.strip.empty? }
149
+ end
150
+
151
+ # Form encodes a hash of parameters.
152
+ # @param [Hash] The hash of parameters to encode.
153
+ # @return [Hash] A hash with the same parameters form encoded.
154
+ def self.form_encode_parameters(form_parameters)
155
+ encoded = {}
156
+ form_parameters.each do |key, value|
157
+ encoded.merge!(APIHelper.form_encode(value, key, formatting:
158
+ Configuration.array_serialization))
159
+ end
160
+ encoded
161
+ end
162
+
163
+ def self.custom_merge(a, b)
164
+ x = {}
165
+ a.each do |key, value_a|
166
+ b.each do |k, value_b|
167
+ next unless key == k
168
+ x[k] = []
169
+ if value_a.instance_of? Array
170
+ value_a.each do |v|
171
+ x[k].push(v)
172
+ end
173
+ else
174
+ x[k].push(value_a)
175
+ end
176
+ if value_b.instance_of? Array
177
+ value_b.each do |v|
178
+ x[k].push(v)
179
+ end
180
+ else
181
+ x[k].push(value_b)
182
+ end
183
+ a.delete(k)
184
+ b.delete(k)
185
+ end
186
+ end
187
+ x.merge!(a)
188
+ x.merge!(b)
189
+ x
190
+ end
191
+
192
+ # Form encodes an object.
193
+ # @param [Dynamic] An object to form encode.
194
+ # @param [String] The name of the object.
195
+ # @return [Hash] A form encoded representation of the object in the form
196
+ # of a hash.
197
+ def self.form_encode(obj, instance_name, formatting: 'indexed')
198
+ retval = {}
199
+
200
+ serializable_types = [String, Numeric, TrueClass,
201
+ FalseClass, Date, DateTime]
202
+
203
+ # If this is a structure, resolve it's field names.
204
+ obj = obj.to_hash if obj.is_a? BaseModel
205
+
206
+ # Create a form encoded hash for this object.
207
+ if obj.nil?
208
+ nil
209
+ elsif obj.instance_of? Array
210
+ if formatting == 'indexed'
211
+ obj.each_with_index do |value, index|
212
+ retval.merge!(APIHelper.form_encode(value, instance_name + '[' +
213
+ index.to_s + ']'))
214
+ end
215
+ elsif serializable_types.map { |x| obj[0].is_a? x }.any?
216
+ obj.each do |value|
217
+ abc = if formatting == 'unindexed'
218
+ APIHelper.form_encode(value, instance_name + '[]',
219
+ formatting: formatting)
220
+ else
221
+ APIHelper.form_encode(value, instance_name,
222
+ formatting: formatting)
223
+ end
224
+ retval = APIHelper.custom_merge(retval, abc)
225
+ # print retval
226
+ end
227
+ else
228
+ obj.each_with_index do |value, index|
229
+ retval.merge!(APIHelper.form_encode(value, instance_name + '[' +
230
+ index.to_s + ']', formatting: formatting))
231
+ end
232
+ end
233
+ elsif obj.instance_of? Hash
234
+ obj.each do |key, value|
235
+ retval.merge!(APIHelper.form_encode(value, instance_name + '[' +
236
+ key + ']', formatting: formatting))
237
+ end
238
+ else
239
+ retval[instance_name] = obj
240
+ end
241
+ retval
242
+ end
243
+
244
+ # Safely converts a string into an rfc3339 DateTime object
245
+ # @param [String] The datetime string
246
+ # @return [DateTime] A DateTime object of rfc3339 format
247
+ def self.rfc3339(date_time)
248
+ # missing timezone information
249
+ if date_time.end_with?('Z') || date_time.index('+')
250
+ DateTime.rfc3339(date_time)
251
+ else
252
+ DateTime.rfc3339(date_time + 'Z')
253
+ end
254
+ end
255
+ end
256
+ end
257
+
258
+ # Extend types to support to_bool.
259
+ module ToBoolean
260
+ def to_bool
261
+ return true if self == true || to_s.strip =~ /^(true|yes|y|1)$/i
262
+ false
263
+ end
264
+ end
265
+
266
+ # Extend NilClass type to support to_bool.
267
+ class NilClass; include ToBoolean; end
268
+ # Extend TrueClass type to support to_bool.
269
+ class TrueClass; include ToBoolean; end
270
+ # Extend FalseClass type to support to_bool.
271
+ class FalseClass; include ToBoolean; end
272
+ # Extend Numeric type to support to_bool.
273
+ class Numeric; include ToBoolean; end
274
+ # Extend String type to support to_bool.
275
+ class String; include ToBoolean; end