class RailFeeds::NationalRail::HTTPClient

A wrapper class for ::Net::HTTP

Public Class Methods

new(credentials: nil, **args) click to toggle source
Calls superclass method RailFeeds::HTTPClient::new
# File lib/rail_feeds/national_rail/http_client.rb, line 7
def initialize(credentials: nil, **args)
  credentials ||= RailFeeds::NationalRail::Credentials
  super
end

Public Instance Methods

fetch(path) click to toggle source

Fetch path from server. @param [String] path The path to fetch. @yield contents

@yieldparam [IO] file Either a Tempfile or StringIO.
Calls superclass method RailFeeds::HTTPClient#fetch
# File lib/rail_feeds/national_rail/http_client.rb, line 16
def fetch(path)
  super "https://opendata.nationalrail.co.uk/#{path}", 'X-Auth-Token' => auth_token
end

Private Instance Methods

auth_token() click to toggle source

rubocop:disable Metrics/AbcSize

# File lib/rail_feeds/national_rail/http_client.rb, line 23
def auth_token
  return @auth_token if !@auth_token.nil? && @auth_token_expires_at >= Time.now

  logger.info 'Getting an auth token for national rail.'
  response = Net::HTTP.post_form(
    URI('https://opendata.nationalrail.co.uk/authenticate'),
    credentials.to_h
  )
  response.value # Raise an exception if not successful
  data = JSON.parse(response.body)
  logger.debug "Got auth token data: #{data.inspect}"
  token = data.fetch('token')

  # Token expires in 1 hour. Using 55 minutes provides a safety margin.
  @auth_token_expires_at = Time.now + (55 * 60)
  logger.debug "Auth token expires at #{@auth_token_expires_at}."

  @auth_token = token
end