Created
April 20, 2020 16:42
-
-
Save benhickson/b71fe4db3f4c6aef545103d9a1d41503 to your computer and use it in GitHub Desktop.
https://traversal.ist/how-to-fake-an-api - MapsAPI class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'json' | |
class MapsAPI | |
def get_directions(origin, destination, real_request = false) | |
response = api_endpoint(google_maps_api_key(real_request), origin, destination, real_request) | |
parsed = JSON.parse(response) | |
{ | |
'status': parsed['status'], | |
'distance': parsed['routes'][0]['legs'][0]['distance']['value'].to_i, | |
'duration': parsed['routes'][0]['legs'][0]['duration']['value'].to_i | |
} | |
end | |
private | |
def google_maps_api_key(real_request = false) | |
if real_request | |
Rails.application.credentials.google_maps[:api_key] | |
else | |
'FAKEKEY_FJ8302S93LAAZD' | |
end | |
end | |
def api_endpoint(api_key, origin, destination, real_request = false) | |
# If any of the fields are not provided | |
if api_key == '' || origin == '' || destination == '' | |
# return early with a status | |
return JSON.generate({'status': 'BAD REQUEST'}) | |
end | |
if real_request | |
return RestClient.get("https://maps.googleapis.com/maps/api/directions/json?&origin=#{origin}&destination=#{destination}&key=#{api_key}") | |
end | |
# some code that returns what we want | |
distance_value = 17981 | |
duration_value = 2404 | |
status = 'OK' | |
# re-create the data structure of the API we're modeling. | |
output_hash = { | |
"geocoded_waypoints": [], | |
"routes": [ | |
{"legs": [ | |
{ | |
"distance": {"value": distance_value}, | |
"duration": {"value": duration_value} | |
} | |
]} | |
], | |
"status": "OK" | |
} | |
JSON.generate(output_hash) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment