/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

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