PageRenderTime 51ms CodeModel.GetById 18ms app.highlight 29ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/bundle/jruby/2.1/gems/redis-3.0.7/lib/redis/subscribe.rb

https://github.com/delowong/logstash
Ruby | 83 lines | 63 code | 18 blank | 2 comment | 4 complexity | e997be9f7905e987541ad94c905ee8f7 MD5 | raw file
 1class Redis
 2  class SubscribedClient
 3    def initialize(client)
 4      @client = client
 5    end
 6
 7    def call(command)
 8      @client.process([command])
 9    end
10
11    def subscribe(*channels, &block)
12      subscription("subscribe", "unsubscribe", channels, block)
13    end
14
15    def psubscribe(*channels, &block)
16      subscription("psubscribe", "punsubscribe", channels, block)
17    end
18
19    def unsubscribe(*channels)
20      call([:unsubscribe, *channels])
21    end
22
23    def punsubscribe(*channels)
24      call([:punsubscribe, *channels])
25    end
26
27  protected
28
29    def subscription(start, stop, channels, block)
30      sub = Subscription.new(&block)
31
32      unsubscribed = false
33
34      begin
35        @client.call_loop([start, *channels]) do |line|
36          type, *rest = line
37          sub.callbacks[type].call(*rest)
38          unsubscribed = type == stop && rest.last == 0
39          break if unsubscribed
40        end
41      ensure
42        # No need to unsubscribe here. The real client closes the connection
43        # whenever an exception is raised (see #ensure_connected).
44      end
45    end
46  end
47
48  class Subscription
49    attr :callbacks
50
51    def initialize
52      @callbacks = Hash.new do |hash, key|
53        hash[key] = lambda { |*_| }
54      end
55
56      yield(self)
57    end
58
59    def subscribe(&block)
60      @callbacks["subscribe"] = block
61    end
62
63    def unsubscribe(&block)
64      @callbacks["unsubscribe"] = block
65    end
66
67    def message(&block)
68      @callbacks["message"] = block
69    end
70
71    def psubscribe(&block)
72      @callbacks["psubscribe"] = block
73    end
74
75    def punsubscribe(&block)
76      @callbacks["punsubscribe"] = block
77    end
78
79    def pmessage(&block)
80      @callbacks["pmessage"] = block
81    end
82  end
83end