Class: TripSpark::Client::Vehicles

Inherits:
API
  • Object
show all
Extended by:
Memoist
Defined in:
lib/tripspark_api/client/vehicles.rb

Instance Method Summary collapse

Methods inherited from API

#get_request, include_api, #post_request, #refresh, require_all, singleton

Methods included from TripSpark::Connection

#adapter, #connection, #register_adapter

Instance Method Details

#by_pattern(*routes) ⇒ Object

Return a Hash of Pattern objects to Vehicles on that pattern. If ‘routes` is provided (as an array of route keys), only vehicles on those routes will be included.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/tripspark_api/client/vehicles.rb', line 8

def by_pattern *routes
  params = _route_direction_pair_params(routes)
  routes = post_request('/RouteMap/GetVehicles/', body: params)
  routes.each.with_object({}) do |route, patterns_hash|
    route['VehiclesByPattern'].each do |pat|
      pattern = Pattern.new(pat['Pattern'])
      # Apparently, vehicles can go in multiple directions concurrently,
      # even though that directly conflicts with the idea that vehicles
      # belong to patterns and patterns have one direction.
      # To avoid creating more Vehicle objects that necessary, first clear
      # the Vehicles hash of any duplicates, then create the objects.
      vehicles = pat['Vehicles'].uniq{ |vehicle| vehicle['Key'] }
      patterns_hash[pattern] = vehicles.map{ |vehicle| Vehicle.new(vehicle) }
    end
  end
end

#by_route(*route_keys) ⇒ Object

Return a Hash of Route keys to Vehicles. If ‘route_keys` are given, only those Routes will be included



37
38
39
40
41
# File 'lib/tripspark_api/client/vehicles.rb', line 37

def by_route *route_keys
  list(*route_keys).each.with_object({}) do |vehicle, route_hash|
    (route_hash[vehicle.route.key] ||= []) << vehicle
  end
end

#get(key) ⇒ Object Also known as: find

Return the vehicle whose key matches the given key



45
46
47
# File 'lib/tripspark_api/client/vehicles.rb', line 45

def get key
  list.find{ |vehicle| vehicle.key == key }
end

#list(*routes) ⇒ Object Also known as: all

Return a list of all vehicles currently traveling on routes. If ‘routes` is provided (as an array of route keys), only vehicles on those routes will be included.



29
30
31
# File 'lib/tripspark_api/client/vehicles.rb', line 29

def list *routes
  by_pattern(*routes).values.flatten
end