Class: NationalRail::LiveDepartureBoards

Inherits:
Object
  • Object
show all
Defined in:
lib/national-rail/live_departure_boards.rb

Defined Under Namespace

Classes: SummaryRow

Instance Method Summary collapse

Instance Method Details

#summary(options = {}) ⇒ Object



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
# File 'lib/national-rail/live_departure_boards.rb', line 33

def summary(options = {})
  departing = case options[:type]
  when :departures
    true
  when :arrivals
    false
  else
    true
  end
  if departing
    liveTrainsFrom, liveTrainsTo = options[:from], options[:to]
    origin_or_destination = :destination
  else
    liveTrainsFrom, liveTrainsTo = options[:to], options[:from]
    origin_or_destination = :origin
  end
  url = "http://ojp.nationalrail.co.uk/en/s/ldb/liveTrainsJson"
  params = { "departing" => departing.to_s, "liveTrainsFrom" => liveTrainsFrom, "liveTrainsTo" => liveTrainsTo }
  uri = URI.parse("#{url}?#{params.to_query}")
  response = Net::HTTP.get_response(uri)
  json = ActiveSupport::JSON.decode(response.body)
  trains = json["trains"].map do |row|
    service_id = CGI.unescape(%r{/en/s/ldbdetails/([^\?]+)}.match(row[5])[1])
    SummaryRow.new(
      :service_id => service_id,
      :due => row[1],
      origin_or_destination => row[2],
      :status => CGI.unescapeHTML(row[3]).split("<br/>").map(&:strip),
      :platform => row[4]
    )
  end
end