class TransilienRealtime::Base

Constants

ACCEPT_STRINGS
API_TARGETS
API_VERSION
DOCUMENTATION_VERSION

Public Class Methods

new(user: ENV['RTT_API_USER'], pwd: ENV['RTT_API_PWD'], target: :production) click to toggle source
# File lib/transilien_realtime/base.rb, line 19
def initialize(user: ENV['RTT_API_USER'], pwd: ENV['RTT_API_PWD'], target: :production)
  @user = user
  @pwd = pwd

  @target = target
end

Public Instance Methods

body() click to toggle source
# File lib/transilien_realtime/base.rb, line 47
def body; @body; end
content() click to toggle source
# File lib/transilien_realtime/base.rb, line 48
def content; @content; end
json() click to toggle source
# File lib/transilien_realtime/base.rb, line 41
def json
  return nil unless trains
  "[#{trains.map(&:to_json).join(',')}]"
end
next(from:, to: nil) click to toggle source
# File lib/transilien_realtime/base.rb, line 26
def next(from:, to: nil)
  raise ArgumentError, 'from param is mandatory' unless from
  fetch(build_request(from, to))
  self
end
response() click to toggle source
# File lib/transilien_realtime/base.rb, line 46
def response; @response; end
trains() click to toggle source
# File lib/transilien_realtime/base.rb, line 50
def trains
  @trains ||= begin
    return nil unless xml_document
    trains = []
    xml_document.xpath('//train').each do |train_node|
      begin
        trains << Train.from_xml(train_node)
      rescue Exception => e
        $stderr << "FAILURE! WAS READING #{train_node.to_s.inspect}"
        raise e
      end
    end
    trains.freeze
  end 
end
xml() click to toggle source
# File lib/transilien_realtime/base.rb, line 37
def xml
  @content
end
xml_document() click to toggle source
# File lib/transilien_realtime/base.rb, line 32
def xml_document
  return nil unless @content
  Nokogiri::XML(@content)
end

Protected Instance Methods

build_request(from, to) click to toggle source
# File lib/transilien_realtime/base.rb, line 68
def build_request(from, to)
  request = API_TARGETS[@target]
  request += "gare/#{from}/depart/"
  request += "#{to}/" if to
  request
end
fetch(request) click to toggle source
# File lib/transilien_realtime/base.rb, line 75
def fetch(request)
  @trains = nil # destroy cache
  @response = HTTP.basic_auth(user: @user, pass: @pwd).headers(accept: ACCEPT_STRINGS[API_VERSION]).get(request)#.body
  @body = @response.body
  @content = @body.readpartial
end