-
Notifications
You must be signed in to change notification settings - Fork 0
/
mbta.rb
71 lines (63 loc) · 2.08 KB
/
mbta.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
require 'sinatra'
require 'rest_client'
require 'sinatra/reloader' if development?
class Mbta < Sinatra::Application
get '/' do
route_params = api_params.merge(route: "CR-Newburyport")
begin
response = RestClient.get("#{api_url}/vehiclesbyroute", params: route_params)
vehiclesbyroute = JSON.parse(response.body)
inbound = vehiclesbyroute["direction"].select { |d| d["direction_name"] == "Inbound" }
outbound = vehiclesbyroute["direction"].select { |d| d["direction_name"] == "Outbound" }
@inbound_trips = parse_trips(inbound)
@outbound_trips = parse_trips(outbound)
erb :status
rescue RestClient::Exception, Errno::ECONNREFUSED => e
e.message
rescue JSON::ParserError => e
e.message
end
end
def parse_trips(directions)
directions.flat_map do |direction|
direction["trip"].map do |trip|
id = trip["trip_id"]
lat = trip["vehicle"]["vehicle_lat"]
lon = trip["vehicle"]["vehicle_lon"]
schedule = parse_schedule(id)
{
id: id,
name: trip["trip_name"],
map_url: map_url(lat, lon),
map_image_url: map_image_url(lat, lon),
lat: lat,
lon: lon,
speed: trip["vehicle"]["speed"] || 0,
schedule: schedule
}
end
end
end
def parse_schedule(trip_id)
response = RestClient.get("#{api_url}/schedulebytrip", params: api_params.merge(trip: trip_id))
schedule = JSON.parse(response.body)
schedule["stop"].map do |stop|
{
name: stop["stop_name"],
arrival: Time.at(stop["sch_arr_dt"].to_i).strftime("%l:%M %P")
}
end
end
def api_url
"http://realtime.mbta.com/developer/api/v2"
end
def api_params
{ api_key: ENV["MBTA_API_KEY"], format: "json" }
end
def map_url(lat, lon)
"https://www.google.com/maps/place/#{lat},#{lon}"
end
def map_image_url(lat, lon)
"http://maps.google.com/maps/api/staticmap?size=300x300&zoom=15&markers=#{lat},#{lon}"
end
end