pastclimate 0.1.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.
@@ -0,0 +1,390 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "date"
5
+ require "uri"
6
+
7
+ module PastClimate
8
+ # The PastClimate API client. One instance can be shared by many threads.
9
+ #
10
+ # client = PastClimate::Client.new(api_key: ENV["PASTCLIMATE_API_KEY"])
11
+ # response = client.get_daily("gb/london", start_date: "2024-01-01", end_date: "2024-01-31")
12
+ # response.data.first.daily_max_temp
13
+ # response.credits_remaining
14
+ #
15
+ # Every JSON method returns a Response (+data+, +location+, +meta+, +rate_limit+,
16
+ # +credits_used+, +credits_remaining+). With +format: :csv+ the daily and hourly
17
+ # methods return a CsvResponse instead.
18
+ class Client
19
+ DEFAULT_BASE_URL = "https://api.pastclimate.com"
20
+ DEFAULT_TIMEOUT = 30
21
+ DEFAULT_MAX_RETRIES = 2
22
+ DEFAULT_MAX_RETRY_DELAY = 60
23
+ API_KEY_ENV = "PASTCLIMATE_API_KEY"
24
+ BASE_URL_ENV = "PASTCLIMATE_BASE_URL"
25
+ BACKOFF_BASE = 0.5
26
+ UNITS = %w[metric imperial].freeze
27
+ FORMATS = %w[json csv].freeze
28
+ LOOPBACK_HOSTS = %w[localhost 127.0.0.1 ::1 [::1]].freeze
29
+
30
+ attr_reader :base_url, :timeout, :max_retries, :max_retry_delay
31
+
32
+ # @param api_key [String, nil] your key; falls back to ENV["PASTCLIMATE_API_KEY"]
33
+ # @param base_url [String, nil] defaults to ENV["PASTCLIMATE_BASE_URL"], then https://api.pastclimate.com
34
+ # @param timeout [Numeric] seconds, per connection attempt (default 30)
35
+ # @param max_retries [Integer] retries after the first try (default 2)
36
+ # @param max_retry_delay [Numeric] longest wait, in seconds, the client will sleep
37
+ # between tries. A 429 whose Retry-After is longer than this is raised, not waited out.
38
+ # @param transport [#call, nil] a custom HTTP transport (see NetHttpTransport)
39
+ # @param sleeper [#call, nil] called with the seconds to wait; for tests
40
+ # @param random [#call, nil] returns a Float in [0, 1) for backoff jitter; for tests
41
+ def initialize(api_key: nil, base_url: nil, timeout: DEFAULT_TIMEOUT, max_retries: DEFAULT_MAX_RETRIES,
42
+ max_retry_delay: DEFAULT_MAX_RETRY_DELAY, transport: nil, sleeper: nil, random: nil)
43
+ @api_key = clean_api_key(api_key || ENV[API_KEY_ENV])
44
+ @base_url = clean_base_url(base_url || ENV[BASE_URL_ENV] || DEFAULT_BASE_URL)
45
+ @timeout = positive_number(timeout, "timeout")
46
+ @max_retries = non_negative_integer(max_retries, "max_retries")
47
+ @max_retry_delay = non_negative_number(max_retry_delay, "max_retry_delay")
48
+ @transport = transport || NetHttpTransport.new
49
+ @sleeper = sleeper || ->(seconds) { sleep(seconds) }
50
+ @random = random || -> { rand }
51
+ end
52
+
53
+ # The key is never printed.
54
+ def inspect
55
+ "#<PastClimate::Client base_url=#{@base_url.inspect} api_key=[REDACTED]>"
56
+ end
57
+ alias to_s inspect
58
+
59
+ # --- Locations ---------------------------------------------------------
60
+
61
+ # Search places by the start of their name (free). Returns Response whose
62
+ # data is an Array of LocationSearchResult.
63
+ #
64
+ # @param q [String] the start of a place name
65
+ # @param country [String, nil] limit results to one country (two-letter code)
66
+ def search_locations(q, country: nil)
67
+ raise ArgumentError, "q is required" if q.to_s.strip.empty?
68
+
69
+ get("/v1/locations/search", { "q" => q.to_s, "country" => blank_to_nil(country) }) do |data|
70
+ list(data, LocationSearchResult)
71
+ end
72
+ end
73
+
74
+ # The place nearest a point, inside one country (free). data is a NearestLocation.
75
+ def nearest_location(lat:, lon:, country:)
76
+ point = Place.point(lat: lat, lon: lon, country: country)
77
+ get("/v1/locations/nearest", {
78
+ "lat" => Place.format_number(lat), "lon" => Place.format_number(lon), "country" => point.country
79
+ }) { |data| NearestLocation.from_hash(data) }
80
+ end
81
+
82
+ # One location by id (free). data is a LocationDetail.
83
+ #
84
+ # @param id [String, Place] a location id such as "gb/london"
85
+ def get_location(id)
86
+ place = Place.coerce(id)
87
+ raise ArgumentError, "get_location needs a location id such as \"gb/london\"" if place.country
88
+
89
+ country, slug = place.location.split("/", 2)
90
+ raise ArgumentError, "a location id looks like \"gb/london\"" if slug.nil? || country.empty? || slug.empty?
91
+
92
+ get("/v1/locations/#{path_segment(country)}/#{path_segment(slug)}") { |data| LocationDetail.from_hash(data) }
93
+ end
94
+
95
+ # --- Weather -----------------------------------------------------------
96
+
97
+ # Daily weather for each day from +start_date+ to +end_date+, both included.
98
+ # data is an Array of DailyRow, or the CSV text with +format: :csv+.
99
+ #
100
+ # @param location [String, Place]
101
+ # @param start_date [Date, Time, String] first day, YYYY-MM-DD
102
+ # @param end_date [Date, Time, String] last day, YYYY-MM-DD
103
+ # @param units [Symbol, String, nil] :metric (the server default) or :imperial
104
+ # @param format [Symbol, String] :json (default) or :csv
105
+ def get_daily(location, start_date:, end_date:, units: nil, format: :json)
106
+ query = place_query(location).merge(
107
+ "start" => date_param(start_date, "start_date"),
108
+ "end" => date_param(end_date, "end_date"),
109
+ "units" => units_param(units)
110
+ )
111
+ weather_get("/v1/daily", query, format) { |data| list(data, DailyRow) }
112
+ end
113
+
114
+ # Hourly weather for +days+ consecutive local days starting at +date+.
115
+ # data is an Array of HourlyRow, or the CSV text with +format: :csv+.
116
+ #
117
+ # @param days [Integer, nil] number of days; leave nil for the server default
118
+ def get_hourly(location, date:, days: nil, units: nil, format: :json)
119
+ query = place_query(location).merge(
120
+ "date" => date_param(date, "date"),
121
+ "days" => days_param(days),
122
+ "units" => units_param(units)
123
+ )
124
+ weather_get("/v1/hourly", query, format) { |data| list(data, HourlyRow) }
125
+ end
126
+
127
+ # Convenience for get_daily(..., format: :csv). Returns a CsvResponse.
128
+ def get_daily_csv(location, start_date:, end_date:, units: nil)
129
+ get_daily(location, start_date: start_date, end_date: end_date, units: units, format: :csv)
130
+ end
131
+
132
+ # Convenience for get_hourly(..., format: :csv). Returns a CsvResponse.
133
+ def get_hourly_csv(location, date:, days: nil, units: nil)
134
+ get_hourly(location, date: date, days: days, units: units, format: :csv)
135
+ end
136
+
137
+ # One row per calendar month (UTC) for the whole archive. data is an Array of MonthlyRow.
138
+ def get_monthly(location, units: nil)
139
+ get("/v1/monthly", place_query(location).merge("units" => units_param(units))) { |data| list(data, MonthlyRow) }
140
+ end
141
+
142
+ # One row per calendar year (UTC) for the whole archive. data is an Array of YearlyRow.
143
+ def get_yearly(location, units: nil)
144
+ get("/v1/yearly", place_query(location).merge("units" => units_param(units))) { |data| list(data, YearlyRow) }
145
+ end
146
+
147
+ # Climate normals: 12 monthly and 366 day-of-year rows, or only +month+ (1 to 12).
148
+ # data is a NormalsData.
149
+ def get_normals(location, month: nil, units: nil)
150
+ query = place_query(location).merge("month" => month_param(month), "units" => units_param(units))
151
+ get("/v1/normals", query) { |data| NormalsData.from_hash(data) }
152
+ end
153
+
154
+ # The hottest, coldest, wettest and windiest day on file. data is an Array of RecordItem.
155
+ def get_records(location, units: nil)
156
+ get("/v1/records", place_query(location).merge("units" => units_param(units))) { |data| list(data, RecordItem) }
157
+ end
158
+
159
+ # --- Account -----------------------------------------------------------
160
+
161
+ # The countries the archive serves, and the span of published data for each
162
+ # (free). data is a CoverageData.
163
+ def get_coverage(country: nil)
164
+ get("/v1/coverage", { "country" => blank_to_nil(country) }) { |data| CoverageData.from_hash(data) }
165
+ end
166
+
167
+ # Your plan, credit balance and limits (free). data is a MeData.
168
+ def get_me
169
+ get("/v1/me") { |data| MeData.from_hash(data) }
170
+ end
171
+
172
+ private
173
+
174
+ # --- Request plumbing --------------------------------------------------
175
+
176
+ def weather_get(path, query, format, &parser)
177
+ if format_param(format) == "csv"
178
+ get_csv(path, query.merge("format" => "csv"))
179
+ else
180
+ get(path, query, &parser)
181
+ end
182
+ end
183
+
184
+ def get(path, query = {}, &parser)
185
+ raw = perform(build_url(path, query), request_headers(csv: false))
186
+ parse_envelope(raw, parser)
187
+ end
188
+
189
+ def get_csv(path, query)
190
+ raw = perform(build_url(path, query), request_headers(csv: true))
191
+ CsvResponse.new(csv: raw.body.to_s, status: raw.status, headers: Headers.normalize(raw.headers))
192
+ end
193
+
194
+ def request_headers(csv:)
195
+ {
196
+ "Authorization" => "Bearer #{@api_key}",
197
+ "Accept" => csv ? "text/csv, application/json;q=0.9" : "application/json",
198
+ "User-Agent" => "pastclimate-ruby/#{VERSION}"
199
+ }
200
+ end
201
+
202
+ def build_url(path, query)
203
+ pairs = query.reject { |_name, value| value.nil? }
204
+ text = pairs.map { |name, value| "#{query_component(name)}=#{query_component(value)}" }.join("&")
205
+ "#{@base_url}#{path}#{text.empty? ? '' : "?#{text}"}"
206
+ end
207
+
208
+ def query_component(value)
209
+ URI.encode_www_form_component(value.to_s).gsub("+", "%20")
210
+ end
211
+
212
+ def path_segment(value)
213
+ query_component(value)
214
+ end
215
+
216
+ # Sends the request, retrying where it is safe. Returns the 2xx TransportResponse
217
+ # or raises a typed error.
218
+ def perform(url, headers)
219
+ attempt = 0
220
+ loop do
221
+ begin
222
+ raw = @transport.call(method: :get, url: url, headers: headers, timeout: @timeout)
223
+ rescue ConnectionError
224
+ raise if attempt >= @max_retries
225
+
226
+ @sleeper.call(backoff_delay(attempt))
227
+ attempt += 1
228
+ next
229
+ end
230
+
231
+ raw = TransportResponse.new(status: raw.status, headers: Headers.normalize(raw.headers), body: raw.body)
232
+ return raw if raw.status >= 200 && raw.status < 300
233
+
234
+ error = Errors.from_response(raw)
235
+ delay = retry_delay(error, attempt)
236
+ raise error if delay.nil?
237
+
238
+ @sleeper.call(delay)
239
+ attempt += 1
240
+ end
241
+ end
242
+
243
+ # Seconds to wait before the next try, or nil for "do not retry".
244
+ # 429 is retried only when it carries Retry-After (and the wait is not longer
245
+ # than max_retry_delay). 5xx is retried with backoff. Other 4xx never.
246
+ def retry_delay(error, attempt)
247
+ return nil if attempt >= @max_retries
248
+
249
+ if error.status == 429
250
+ wait = error.retry_after
251
+ return nil if wait.nil? || wait > @max_retry_delay
252
+
253
+ wait
254
+ elsif error.status >= 500
255
+ backoff_delay(attempt)
256
+ end
257
+ end
258
+
259
+ def backoff_delay(attempt)
260
+ capped = [BACKOFF_BASE * (2**attempt), @max_retry_delay].min
261
+ capped * (0.5 + (0.5 * @random.call))
262
+ end
263
+
264
+ def parse_envelope(raw, parser)
265
+ json = JSON.parse(raw.body.to_s)
266
+ raise TypeError, "expected a JSON object" unless json.is_a?(Hash)
267
+
268
+ Response.new(
269
+ data: parser.call(json["data"]),
270
+ location: Location.from_hash(json["location"]),
271
+ meta: Meta.from_hash(json["meta"]),
272
+ status: raw.status,
273
+ headers: raw.headers
274
+ )
275
+ rescue JSON::ParserError, TypeError, ArgumentError => e
276
+ raise ServerError.new(
277
+ "The API answered #{raw.status} but the body could not be read (#{e.message}).",
278
+ status: raw.status, code: "invalid_response", headers: raw.headers, body: raw.body
279
+ )
280
+ end
281
+
282
+ def list(data, model)
283
+ return [] if data.nil?
284
+ raise TypeError, "expected a JSON array" unless data.is_a?(Array)
285
+
286
+ data.map { |item| model.from_hash(item) }
287
+ end
288
+
289
+ # --- Parameter handling ------------------------------------------------
290
+
291
+ def place_query(location)
292
+ Place.coerce(location).to_query
293
+ end
294
+
295
+ def units_param(units)
296
+ return nil if units.nil?
297
+
298
+ value = units.to_s.strip.downcase
299
+ raise ArgumentError, "units must be :metric or :imperial, got #{units.inspect}" unless UNITS.include?(value)
300
+
301
+ value
302
+ end
303
+
304
+ def format_param(format)
305
+ value = format.to_s.strip.downcase
306
+ raise ArgumentError, "format must be :json or :csv, got #{format.inspect}" unless FORMATS.include?(value)
307
+
308
+ value
309
+ end
310
+
311
+ def date_param(value, name)
312
+ case value
313
+ when Date, Time then value.strftime("%Y-%m-%d") # DateTime is a Date
314
+ when String
315
+ raise ArgumentError, "#{name} must look like 2024-01-31, got #{value.inspect}" unless value.match?(/\A\d{4}-\d{2}-\d{2}\z/)
316
+
317
+ value
318
+ else
319
+ raise ArgumentError, "#{name} must be a Date, a Time or a YYYY-MM-DD String, got #{value.inspect}"
320
+ end
321
+ end
322
+
323
+ def days_param(days)
324
+ return nil if days.nil?
325
+ raise ArgumentError, "days must be a whole number of at least 1" unless days.is_a?(Integer) && days >= 1
326
+
327
+ days.to_s
328
+ end
329
+
330
+ def month_param(month)
331
+ return nil if month.nil?
332
+ raise ArgumentError, "month must be a whole number from 1 to 12" unless month.is_a?(Integer) && month.between?(1, 12)
333
+
334
+ month.to_s
335
+ end
336
+
337
+ def blank_to_nil(value)
338
+ text = value.to_s.strip
339
+ text.empty? ? nil : text
340
+ end
341
+
342
+ # --- Settings ----------------------------------------------------------
343
+
344
+ def clean_api_key(value)
345
+ key = value.to_s.strip
346
+ if key.empty?
347
+ raise ConfigurationError,
348
+ "No API key. Pass api_key: or set the #{API_KEY_ENV} environment variable."
349
+ end
350
+ raise ConfigurationError, "The API key contains characters that are not allowed in a header." if key.match?(/[[:cntrl:]]|\s/)
351
+
352
+ key
353
+ end
354
+
355
+ def clean_base_url(value)
356
+ text = value.to_s.strip.sub(%r{/+\z}, "")
357
+ uri = begin
358
+ URI.parse(text)
359
+ rescue URI::InvalidURIError
360
+ nil
361
+ end
362
+ unless uri && %w[http https].include?(uri.scheme) && uri.host
363
+ raise ConfigurationError, "base_url must be an http(s) URL, got #{value.inspect}"
364
+ end
365
+ if uri.scheme == "http" && !LOOPBACK_HOSTS.include?(uri.host)
366
+ raise ConfigurationError, "base_url must use https (plain http is allowed only for localhost), got #{value.inspect}"
367
+ end
368
+
369
+ text
370
+ end
371
+
372
+ def positive_number(value, name)
373
+ raise ConfigurationError, "#{name} must be a positive number" unless value.is_a?(Numeric) && value.positive?
374
+
375
+ value
376
+ end
377
+
378
+ def non_negative_number(value, name)
379
+ raise ConfigurationError, "#{name} must be a number, 0 or more" unless value.is_a?(Numeric) && value >= 0
380
+
381
+ value
382
+ end
383
+
384
+ def non_negative_integer(value, name)
385
+ raise ConfigurationError, "#{name} must be a whole number, 0 or more" unless value.is_a?(Integer) && value >= 0
386
+
387
+ value
388
+ end
389
+ end
390
+ end
@@ -0,0 +1,139 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module PastClimate
6
+ # Base class of everything this gem raises on purpose.
7
+ class Error < StandardError; end
8
+
9
+ # The client was set up wrongly (for example, no API key).
10
+ class ConfigurationError < Error; end
11
+
12
+ # The request never produced an HTTP answer: DNS, TLS, connection reset or timeout.
13
+ class ConnectionError < Error
14
+ def initialize(message = "Could not reach the PastClimate API.", timeout: false)
15
+ super(message)
16
+ @timeout = timeout
17
+ end
18
+
19
+ # True when the call timed out.
20
+ def timeout?
21
+ @timeout
22
+ end
23
+ end
24
+
25
+ # The API answered with an error. Branch on the subclass, or on +code+.
26
+ #
27
+ # Every error carries the HTTP +status+, the stable error +code+, the human
28
+ # +message+ and a +docs_url+. When the server did not send the API's error
29
+ # body (for example a proxy 502), +code+ is "http_<status>" and +docs_url+
30
+ # is nil.
31
+ class ApiError < Error
32
+ attr_reader :status, :code, :docs_url, :headers, :rate_limit, :retry_after, :upgrade_url, :body
33
+
34
+ def initialize(message = nil, status: nil, code: nil, docs_url: nil, headers: {}, body: nil)
35
+ super(message || "The PastClimate API returned an error.")
36
+ @status = status
37
+ @code = code
38
+ @docs_url = docs_url
39
+ @headers = headers
40
+ @body = body
41
+ @rate_limit = RateLimit.from_headers(headers)
42
+ @retry_after = Headers.retry_after(headers)
43
+ @upgrade_url = headers["x-upgrade-url"]
44
+ end
45
+ end
46
+
47
+ # No key, a bad key, a revoked key, or an account that cannot make calls.
48
+ # Codes: missing_key, invalid_key, key_revoked, email_not_verified, account_suspended.
49
+ class AuthenticationError < ApiError; end
50
+
51
+ # The request is not valid. Fix it; retrying will not help.
52
+ # Codes: invalid_request, range_too_large, key_in_query, cors_not_supported, method_not_allowed.
53
+ class InvalidRequestError < ApiError; end
54
+
55
+ # No such place, nothing published for the request, or a place that cannot be served.
56
+ # Codes: location_not_found, not_published, not_found, location_blocked.
57
+ class NotFoundError < ApiError; end
58
+
59
+ # Your plan does not include this request. Code: plan_required.
60
+ class PlanRequiredError < ApiError; end
61
+
62
+ # Too many requests (per minute or per day). +retry_after+ says how long to wait.
63
+ # Codes: rate_limited, daily_request_cap_reached.
64
+ class RateLimitedError < ApiError; end
65
+
66
+ # Credits are used up. Code: quota_exceeded. On a plan whose credits are one-time
67
+ # there is no +retry_after+, because waiting does not help.
68
+ class QuotaExceededError < ApiError; end
69
+
70
+ # Something went wrong on the server, or the API is unavailable.
71
+ # Codes: internal_error, api_disabled, metering_unavailable. Also raised
72
+ # (code "invalid_response") when a success answer cannot be read.
73
+ class ServerError < ApiError; end
74
+
75
+ # Maps an HTTP error answer to one of the classes above.
76
+ module Errors
77
+ CODE_CLASSES = {
78
+ "missing_key" => AuthenticationError,
79
+ "invalid_key" => AuthenticationError,
80
+ "key_revoked" => AuthenticationError,
81
+ "email_not_verified" => AuthenticationError,
82
+ "account_suspended" => AuthenticationError,
83
+ "plan_required" => PlanRequiredError,
84
+ "invalid_request" => InvalidRequestError,
85
+ "range_too_large" => InvalidRequestError,
86
+ "key_in_query" => InvalidRequestError,
87
+ "cors_not_supported" => InvalidRequestError,
88
+ "method_not_allowed" => InvalidRequestError,
89
+ "location_not_found" => NotFoundError,
90
+ "not_published" => NotFoundError,
91
+ "not_found" => NotFoundError,
92
+ "location_blocked" => NotFoundError,
93
+ "rate_limited" => RateLimitedError,
94
+ "daily_request_cap_reached" => RateLimitedError,
95
+ "quota_exceeded" => QuotaExceededError,
96
+ "daily_cap_reached" => QuotaExceededError,
97
+ "internal_error" => ServerError,
98
+ "api_disabled" => ServerError,
99
+ "metering_unavailable" => ServerError
100
+ }.freeze
101
+
102
+ # Builds (does not raise) the error for a non-2xx +response+ (a TransportResponse).
103
+ def self.from_response(response)
104
+ status = response.status
105
+ body = parse_body(response.body)
106
+ detail = body.is_a?(Hash) ? body["error"] : nil
107
+
108
+ if detail.is_a?(Hash) && detail["code"]
109
+ code = detail["code"].to_s
110
+ message = detail["message"] || "The PastClimate API returned an error (#{code})."
111
+ docs_url = detail["docs_url"]
112
+ else
113
+ code = "http_#{status}"
114
+ message = "The API answered HTTP #{status} without an error body."
115
+ docs_url = nil
116
+ end
117
+
118
+ klass = CODE_CLASSES[code] || class_for_status(status)
119
+ klass.new(message, status: status, code: code, docs_url: docs_url, headers: response.headers, body: response.body)
120
+ end
121
+
122
+ def self.class_for_status(status)
123
+ case status
124
+ when 401 then AuthenticationError
125
+ when 400, 405 then InvalidRequestError
126
+ when 404 then NotFoundError
127
+ when 429 then RateLimitedError
128
+ when 500..599 then ServerError
129
+ else ApiError
130
+ end
131
+ end
132
+
133
+ def self.parse_body(text)
134
+ JSON.parse(text.to_s)
135
+ rescue JSON::ParserError
136
+ nil
137
+ end
138
+ end
139
+ end
@@ -0,0 +1,88 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "date"
4
+ require "time"
5
+
6
+ module PastClimate
7
+ # Base class of the response models. A model reads the fields it declares and
8
+ # ignores the rest, so new server fields never break old code. Models are frozen.
9
+ # Use +to_h+ for a plain Hash and +raw+ for the original JSON Hash.
10
+ class Model
11
+ class << self
12
+ def attributes
13
+ @attributes ||= {}
14
+ end
15
+
16
+ # Declares a field. +type+ is :string, :integer, :float, :boolean, :date
17
+ # (a Date), :time (a UTC Time), a Model subclass, or [ModelSubclass] for a list.
18
+ def attribute(name, type = :string)
19
+ attributes[name] = type
20
+ attr_reader name
21
+ end
22
+
23
+ def from_hash(hash)
24
+ return nil if hash.nil?
25
+ raise ArgumentError, "expected a JSON object for #{self}, got #{hash.class}" unless hash.is_a?(Hash)
26
+
27
+ new(hash)
28
+ end
29
+
30
+ def coerce(value, type)
31
+ return nil if value.nil?
32
+
33
+ case type
34
+ when :string then value.to_s
35
+ when :integer then value.is_a?(Numeric) ? value.to_i : Integer(value)
36
+ when :float then Float(value)
37
+ when :boolean then boolean(value)
38
+ when :date then Date.iso8601(value.to_s)
39
+ when :time then Time.iso8601(value.to_s).utc
40
+ when Array then Array(value).map { |item| type.first.from_hash(item) }
41
+ else type.from_hash(value)
42
+ end
43
+ end
44
+
45
+ def boolean(value)
46
+ return value if value == true || value == false
47
+
48
+ value.to_s == "true"
49
+ end
50
+ end
51
+
52
+ attr_reader :raw
53
+
54
+ def initialize(hash = {})
55
+ @raw = hash
56
+ self.class.attributes.each do |name, type|
57
+ instance_variable_set("@#{name}", self.class.coerce(hash[name.to_s], type))
58
+ end
59
+ freeze
60
+ end
61
+
62
+ def to_h
63
+ self.class.attributes.each_key.each_with_object({}) do |name, result|
64
+ value = public_send(name)
65
+ result[name] =
66
+ case value
67
+ when Model then value.to_h
68
+ when Array then value.map { |item| item.is_a?(Model) ? item.to_h : item }
69
+ else value
70
+ end
71
+ end
72
+ end
73
+
74
+ def ==(other)
75
+ other.class == self.class && other.to_h == to_h
76
+ end
77
+ alias eql? ==
78
+
79
+ def hash
80
+ [self.class, to_h].hash
81
+ end
82
+
83
+ def inspect
84
+ fields = self.class.attributes.each_key.map { |name| "#{name}=#{public_send(name).inspect}" }
85
+ "#<#{self.class.name} #{fields.join(' ')}>"
86
+ end
87
+ end
88
+ end