Class: EZMQ::Subscriber

Inherits:
Socket
  • Object
show all
Defined in:
lib/ezmq.rb

Overview

Subscribe socket that listens for messages with an optional topic.

Instance Attribute Summary (collapse)

Attributes inherited from Socket

#context, #decode, #encode, #socket

Instance Method Summary (collapse)

Methods inherited from Socket

#bind, #connect, #receive, #send

Constructor Details

- (Publisher) initialize(action: -> m { puts m }, **options)

Note:

The default behaviour is to output and messages received to STDOUT.

Creates a new Subscriber socket.

Parameters:

  • action (lambda)

    the action to perform when a message is received.

  • options (Hash)

    optional parameters

Options Hash (**options):

  • topic (String)

    a topic to subscribe to.

See Also:



187
188
189
190
191
# File 'lib/ezmq.rb', line 187

def initialize(action: -> m { puts m }, **options)
  @action = action
  super :connect, ZMQ::SUB, options
  subscribe options[:topic] if options[:topic]
end

Instance Attribute Details

- (Object) action

Returns the value of attribute action



172
173
174
# File 'lib/ezmq.rb', line 172

def action
  @action
end

Instance Method Details

- (void) listen(handler: -> { @action.call(receive) })

This method returns an undefined value.

By default, waits for a message and calls @action with the message.

Parameters:

  • handler (lambda)

    how requests are handled.



225
226
227
# File 'lib/ezmq.rb', line 225

def listen(handler: -> { @action.call(receive) })
  loop { handler.call }
end

- (Boolean) subscribe(topic)

Note:

By default, a Subscriber filters all incoming messages. Without

Establishes a new message filter on the socket.

calling subscribe at least once, no messages will be accepted. If topic was provided, #initialize calls #subscribe automatically.

prefix will be accepted.

Parameters:

  • topic (String)

    a topic to subscribe to. Messages matching this

Returns:

  • (Boolean)

    was subscription successful?



204
205
206
# File 'lib/ezmq.rb', line 204

def subscribe(topic)
  @socket.setsockopt(ZMQ::SUBSCRIBE, topic) == 0 ? true : false
end

- (Boolean) unsubscribe(topic)

Removes a message filter (as set with subscribe) from the socket.

Parameters:

  • topic (String)

    the topic to unsubscribe from. If multiple filters with the same topic are set, this will only remove one.

Returns:

  • (Boolean)

    was unsubscription successful?



215
216
217
# File 'lib/ezmq.rb', line 215

def unsubscribe(topic)
  @socket.setsockopt(ZMQ::UNSUBSCRIBE, topic) == 0 ? true : false
end