Module: Ably::Modules::MessageEmitter

Included in:
Realtime::Channel, Realtime::Presence
Defined in:
lib/ably/modules/message_emitter.rb

Overview

Message emitter, subscriber and unsubscriber (Pub/Sub) functionality common to Channels and Presence In addition to standard Pub/Sub functionality, it allows subscribers to subscribe to :all.

Instance Method Summary collapse

Instance Method Details

#emit_message(name, payload) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Emit a message to message subscribers

param name [String,Symbol] the event name param payload [Object] the event object to emit



52
53
54
55
# File 'lib/ably/modules/message_emitter.rb', line 52

def emit_message(name, payload)
  message_emitter_subscriptions[:all].each { |cb| cb.call(payload) }
  message_emitter_subscriptions[name].each { |cb| cb.call(payload) } if name
end

#subscribe(*names) {|Object| ... } ⇒ void

This method returns an undefined value.

Subscribe to events on this object

Parameters:

  • names (String, Symbol)

    Optional, the event name(s) to subscribe to. Defaults to ‘:all` events

Yields:

  • (Object)

    For each event, the provided block is called with the event payload object

Raises:

  • (ArgumentError)


14
15
16
17
18
19
20
# File 'lib/ably/modules/message_emitter.rb', line 14

def subscribe(*names, &callback)
  raise ArgumentError, 'Block required to subscribe to events' unless block_given?
  names = :all unless names && !names.empty?
  Array(names).uniq.each do |name|
    message_emitter_subscriptions[message_emitter_subscriptions_message_name_key(name)] << callback
  end
end

#unsubscribe(*names, &callback) ⇒ void

This method returns an undefined value.

Unsubscribe the matching block for events on the this object. If a block is not provided, all subscriptions will be unsubscribed

Parameters:

  • names (String, Symbol)

    Optional, the event name(s) to unsubscribe from. Defaults to ‘:all` events



29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/ably/modules/message_emitter.rb', line 29

def unsubscribe(*names, &callback)
  names = :all unless names && !names.empty?
  Array(names).each do |name|
    if name == :all
      message_emitter_subscriptions.keys
    else
      Array(message_emitter_subscriptions_message_name_key(name))
    end.each do |key|
      message_emitter_subscriptions[key].delete_if do |block|
        !block_given? || callback == block
      end
    end
  end
end