Class: TickingAway::WorldTime
- Inherits:
-
Object
- Object
- TickingAway::WorldTime
- Defined in:
- lib/ticking_away/world_time.rb
Overview
Class to get time from the World Time Api or another Api with the same spec
Constant Summary collapse
- UNKNOWN_LOCATION_RESPONSE =
{ 'error' => 'unknown location' }.freeze
Class Method Summary collapse
- .call_api(request_url) ⇒ Object
- .handle_response(response, request_url) ⇒ Object
- .parse_response(body) ⇒ Object
- .time_at(base_url, tz_info) ⇒ Object
Class Method Details
.call_api(request_url) ⇒ Object
21 22 23 24 25 |
# File 'lib/ticking_away/world_time.rb', line 21 def call_api(request_url) HTTParty.get(request_url) rescue => e raise TickingAway::Errors::TimeTravelIsHard, e. end |
.handle_response(response, request_url) ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/ticking_away/world_time.rb', line 27 def handle_response(response, request_url) # Convert JSON response to Hash, handling an empty or nil body parsed_response = parse_response(response.body) case response.code when 200 raise TickingAway::Errors::UnrecognizedTimeZone, 'Error: non-time response' unless parsed_response.is_a?(Hash) puts "Event: Retreived current time for #{parsed_response['timezone']}: #{parsed_response['datetime']}" when 404 # Differentiate between an unknown location response and a random 404 by checking the response body if parsed_response.eql?(UNKNOWN_LOCATION_RESPONSE) raise TickingAway::Errors::UnrecognizedTimeZone, "Error: Unrecognized Time Zone #{request_url}" end raise TickingAway::Errors::TimeTravelIsHard, "Error: 404 response for #{request_url}" else raise TickingAway::Errors::TimeTravelIsHard, "Error: #{response.code} #{parsed_response}" end # Convert the time from a RFC3339 formatted string to a Time object Time.parse(parsed_response['datetime']) end |
.parse_response(body) ⇒ Object
51 52 53 54 55 |
# File 'lib/ticking_away/world_time.rb', line 51 def parse_response(body) JSON.parse(body) rescue => e raise TickingAway::Errors::TimeTravelIsHard, e. end |
.time_at(base_url, tz_info) ⇒ Object
14 15 16 17 18 19 |
# File 'lib/ticking_away/world_time.rb', line 14 def time_at(base_url, tz_info) request_url = "#{base_url}/timezone/#{tz_info}" response = call_api(request_url) handle_response(response, request_url) end |