class RailFeeds::NetworkRail::StompClient

A wrapper class for ::Stomp::Client which provides durable subscriptions

Constants

HOST
PORT

Public Class Methods

new(credentials: Credentials, logger: nil) click to toggle source

Initialize a new stomp client. @param [RailFeeds::NetworkRail::Credentials] credentials

The credentials for connecting to the feed.

@param [Logger, nil] logger

The logger for outputting evetns, if nil the global logger will be used.
# File lib/rail_feeds/network_rail/stomp_client.rb, line 18
def initialize(credentials: Credentials, logger: nil)
  @credentials = credentials
  self.logger = logger unless logger.nil?
end

Public Instance Methods

connect() click to toggle source

rubocop:disable Metrics/MethodLength Connect to the network rail server.

# File lib/rail_feeds/network_rail/stomp_client.rb, line 25
def connect
  return if @client && client.open?

  client_options = {
    hosts: [{
      host: HOST,
      port: PORT,
      login: @credentials.username,
      password: @credentials.password
    }],
    connect_headers: {
      'host' => HOST,
      'client-id' => @credentials.username,
      'accept-version' => '1.1',
      'heart-beat' => '5000,10000'
    },
    logger: logger
  }
  @client = Stomp::Client.new client_options
end
disconnect() click to toggle source

Disconnect from the network rail server.

# File lib/rail_feeds/network_rail/stomp_client.rb, line 48
def disconnect
  return if @client.nil?

  @client.close
end
subscribe(topic, headers = {}, &block) click to toggle source

Subscribe to a topic. Will connect to the server if required. Must be passed a block which will be called with each message received. @param [String, to_s] topic

The topic to subscribe to (e.g. "TSR_WESS_ROUTE" or "TD_ALL_SIG_AREA").

@param [Hash] headers

Extra headers to pass to the server.
# File lib/rail_feeds/network_rail/stomp_client.rb, line 61
def subscribe(topic, headers = {}, &block)
  connect if @client.nil? || @client.closed?
  headers['activemq.subscriptionName'] ||= "#{::Socket.gethostname}+#{topic}"
  headers['id'] ||= @client.uuid
  headers['ack'] ||= 'client'
  @client.subscribe "/topic/#{topic}", headers, &block
end