Class: Msngr::Messenger

Inherits:
Object
  • Object
show all
Defined in:
lib/msngr/messenger.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client) ⇒ Receiver

Initializes a new Messenger.

Parameters:


23
24
25
26
27
# File 'lib/msngr/messenger.rb', line 23

def initialize(client)
  @client    = client
  @receivers = []
  @mutex     = Mutex.new
end

Instance Attribute Details

#clientMsngr::Clients::* (readonly)

A client object interface to receive messages from.

Returns:


9
10
11
# File 'lib/msngr/messenger.rb', line 9

def client
  @client
end

#receiversArray<Receiver> (readonly)

An Array of Receiver objects to dispatch callbacks/messages to.

Returns:


15
16
17
# File 'lib/msngr/messenger.rb', line 15

def receivers
  @receivers
end

Instance Method Details

#listen!Object

Listens on a new thread. Will auto-restart when crashed in an attempt to recover from exceptions.


55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/msngr/messenger.rb', line 55

def listen!
  Thread.new do
    loop do
      begin
        listen
      rescue => e
        puts "Messenger error occurred:"
        puts "#{e.class.name}"
        puts "#{e.backtrace.join("\n")}"
        puts "Restarting.."
        sleep 1
      end
    end
  end
end

#subscribe(pattern) ⇒ Receiver

Creates and returns a new Receiver and adds it to @receivers so it'll receive messages matching the provided pattern.

Parameters:

  • pattern (Regexp)

Returns:


36
37
38
39
40
# File 'lib/msngr/messenger.rb', line 36

def subscribe(pattern)
  Msngr::Receiver.new(pattern).tap do |receiver|
    @mutex.synchronize { @receivers << receiver }
  end
end

#unsubscribe(receiver) ⇒ Object

Removes the Receiver from @receivers and invokes the receiver's

Parameters:


47
48
49
50
# File 'lib/msngr/messenger.rb', line 47

def unsubscribe(receiver)
  @mutex.synchronize { @receivers.delete(receiver) }
  dispatch(receiver.on_unsubscribe_callbacks, self)
end