Sha256: 66b2ac047f3034c882ef2e75b1acbb08a1322270c8dbf98795646475856f0eef

Contents?: true

Size: 1.49 KB

Versions: 5

Compression:

Stored size: 1.49 KB

Contents

class Redis
  class SubscribedClient
    def initialize(client)
      @client = client
    end

    def call(command)
      @client.process([command])
    end

    def subscribe(*channels, &block)
      subscription("subscribe", "unsubscribe", channels, block)
    end

    def psubscribe(*channels, &block)
      subscription("psubscribe", "punsubscribe", channels, block)
    end

    def unsubscribe(*channels)
      call [:unsubscribe, *channels]
    end

    def punsubscribe(*channels)
      call [:punsubscribe, *channels]
    end

  protected

    def subscription(start, stop, channels, block)
      sub = Subscription.new(&block)

      begin
        @client.call_loop([start, *channels]) do |line|
          type, *rest = line
          sub.callbacks[type].call(*rest)
          break if type == stop && rest.last == 0
        end
      ensure
        send(stop)
      end
    end
  end

  class Subscription
    attr :callbacks

    def initialize
      @callbacks = Hash.new do |hash, key|
        hash[key] = lambda { |*_| }
      end

      yield(self)
    end

    def subscribe(&block)
      @callbacks["subscribe"] = block
    end

    def unsubscribe(&block)
      @callbacks["unsubscribe"] = block
    end

    def message(&block)
      @callbacks["message"] = block
    end

    def psubscribe(&block)
      @callbacks["psubscribe"] = block
    end

    def punsubscribe(&block)
      @callbacks["punsubscribe"] = block
    end

    def pmessage(&block)
      @callbacks["pmessage"] = block
    end
  end
end

Version data entries

5 entries across 5 versions & 2 rubygems

Version Path
redis-3.0.1 lib/redis/subscribe.rb
redis-3.0.0 lib/redis/subscribe.rb
redis-3.0.0.rc2 lib/redis/subscribe.rb
gorsuch-redis-3.0.0.rc1 lib/redis/subscribe.rb
redis-3.0.0.rc1 lib/redis/subscribe.rb