Class: CTA::BusTracker::Parser

Inherits:
Faraday::Response::Middleware
  • Object
show all
Defined in:
lib/cta_redux/faraday_middleware/bus_tracker_parser.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, debug) ⇒ Parser

Returns a new instance of Parser.



4
5
6
7
# File 'lib/cta_redux/faraday_middleware/bus_tracker_parser.rb', line 4

def initialize(app, debug)
  @debug = debug
  super(app)
end

Instance Method Details

#call(request_env) ⇒ Object



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
# File 'lib/cta_redux/faraday_middleware/bus_tracker_parser.rb', line 9

def call(request_env)
  api_response = nil
  @app.call(request_env).on_complete do |response_env|
    parsed_body = ::MultiXml.parse(response_env.body)

    if has_errors?(parsed_body)
      api_response = CTA::API::Response.new(parsed_body, response_env.body, @debug)
    else
      case response_env.url.to_s
      when /bustime\/.+\/getvehicles/
        api_response = VehiclesResponse.new(parsed_body, response_env.body, @debug)
      when /bustime\/.+\/gettime/
        api_response = TimeResponse.new(parsed_body, response_env.body, @debug)
      when /bustime\/.+\/getroutes/
        api_response = RoutesResponse.new(parsed_body, response_env.body, @debug)
      when /bustime\/.+\/getdirections/
        api_response = DirectionsResponse.new(parsed_body, response_env.body, @debug)
      when /bustime\/.+\/getstops/
        api_response = StopsResponse.new(parsed_body, response_env.body, @debug)
      when /bustime\/.+\/getpatterns/
        api_response = PatternsResponse.new(parsed_body, response_env.body, @debug)
      when /bustime\/.+\/getpredictions/
        api_response = PredictionsResponse.new(parsed_body, response_env.body, @debug)
      when /bustime\/.+\/getservicebulletins/
        api_response = ServiceBulletinsResponse.new(parsed_body, response_env.body, @debug)
      end
    end
  end

  api_response
end

#has_errors?(parsed_body) ⇒ Boolean

Returns:

  • (Boolean)


41
42
43
# File 'lib/cta_redux/faraday_middleware/bus_tracker_parser.rb', line 41

def has_errors?(parsed_body)
  !parsed_body.has_key?("bustime_response") || parsed_body["bustime_response"].has_key?("error")
end