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 { m }, **options)

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:



185
186
187
188
189
# File 'lib/ezmq.rb', line 185

def initialize(action: -> m { 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.



223
224
225
# File 'lib/ezmq.rb', line 223

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?



202
203
204
# File 'lib/ezmq.rb', line 202

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?



213
214
215
# File 'lib/ezmq.rb', line 213

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