Class: Listener

Inherits:
Object
  • Object
show all
Defined in:
lib/listener.rb,
lib/listener/version.rb

Constant Summary collapse

VERSION =
'0.1.0'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(connection, options = {}) ⇒ Listener

Returns a new instance of Listener.



6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/listener.rb', line 6

def initialize(connection, options = {})
  @timeout  = options[:timeout] || 0.1

  @blocks      = {}
  @block_mutex = Mutex.new

  @connection       = connection
  @connection_mutex = Mutex.new

  @thread = Thread.new { listen_loop }
  @thread.priority = options[:priority] || 1
end

Instance Attribute Details

#connectionObject (readonly)

Returns the value of attribute connection.



4
5
6
# File 'lib/listener.rb', line 4

def connection
  @connection
end

Instance Method Details

#listen(*channels, &block) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/listener.rb', line 19

def listen(*channels, &block)
  to_listen = []

  @block_mutex.synchronize do
    channels.each do |channel|
      channel = channel.to_s

      if blocks = @blocks[channel]
        blocks << block
      else
        @blocks[channel] = [block]
        to_listen << channel
      end
    end
  end

  if to_listen.any?
    @connection_mutex.synchronize do
      connection.async_exec to_listen.map{|c| "LISTEN #{c}"}.join('; ')
    end
  end
end

#stopObject



42
43
44
45
# File 'lib/listener.rb', line 42

def stop
  @stop = true
  @thread.join
end