Class: BusTime::Api

Inherits:
Object
  • Object
show all
Defined in:
lib/bus_time/api.rb

Overview

BusTime API interface and response handling

Constant Summary collapse

SUPPORTED_ACTIONS =
%w[
  gettime getroutes getdirections
  getstops getpredictions getservicebulletins
].freeze
BASE_RESPONSE_PROP =
"bustime-response"

Instance Method Summary collapse

Constructor Details

#initialize(api_key, api_url = nil) ⇒ Api

Returns a new instance of Api.



12
13
14
15
# File 'lib/bus_time/api.rb', line 12

def initialize(api_key, api_url = nil)
  @@api_key = api_key
  @api_url = api_url || "https://ctabustracker.com/bustime/api/v2"
end

Instance Method Details

#fetch_bulletinsObject



54
55
56
57
58
59
60
# File 'lib/bus_time/api.rb', line 54

def fetch_bulletins
  request("getservicebulletins")["sb"].map do |bulletin|
    BusTime::Bulletin.new(
      bulletin["nm"]
    )
  end
end

#fetch_directions(route_id) ⇒ Object



38
39
40
41
42
# File 'lib/bus_time/api.rb', line 38

def fetch_directions(route_id)
  request("getdirections", { rt: route_id })["directions"].map do |direction|
    direction["dir"]
  end
end

#fetch_predictions(stop_ids) ⇒ Object



48
49
50
51
52
# File 'lib/bus_time/api.rb', line 48

def fetch_predictions(stop_ids)
  request("getpredictions", { stpid: stop_ids.join(",") })["prd"].map do |prediction|
    assemble_prediction(prediction)
  end
end

#fetch_route(id) ⇒ Object



27
28
29
30
31
32
33
34
35
36
# File 'lib/bus_time/api.rb', line 27

def fetch_route(id)
  route = fetch_routes.find { |returned_route| returned_route.id == id }

  # Get route stops
  route.directions.each do |dir|
    route.stops += fetch_stops(route.id, dir)
  end

  route
end

#fetch_routesObject



21
22
23
24
25
# File 'lib/bus_time/api.rb', line 21

def fetch_routes
  request("getroutes")["routes"].map do |route|
    assemble_route(route)
  end
end

#fetch_routes_and_directions_and_stopsObject



62
63
64
65
66
67
68
69
70
71
72
# File 'lib/bus_time/api.rb', line 62

def fetch_routes_and_directions_and_stops
  routes = fetch_routes

  routes.each do |route|
    route.directions.each do |dir|
      route.stops += fetch_stops(route.id, dir)
    end
  end

  routes
end

#fetch_stops(route_id, direction) ⇒ Object



44
45
46
# File 'lib/bus_time/api.rb', line 44

def fetch_stops(route_id, direction)
  fetch_stops_by_params(rt: route_id, dir: direction)
end

#fetch_timeObject



17
18
19
# File 'lib/bus_time/api.rb', line 17

def fetch_time
  request("gettime")["tm"]
end