class Attention::Subscriber
Uses Redis pub/sub to asynchronously respond to events
Each Subscriber
uses a Redis connection to listen to a channel for events.
Attributes
channel[R]
The channel subscribed to
redis[R]
@!visibility private
Public Class Methods
new(channel, &callback)
click to toggle source
Creates a subscription to the given channel @param channel [String] The channel to listen to @yield The code to execute on a published event @yieldparam channel [String] The channel the subscriber is listening to @yieldparam data [Object] The event published on the channel
# File lib/attention/subscriber.rb, line 28 def initialize(channel, &callback) @channel = channel @redis = Connection.new subscribe &callback end
Public Instance Methods
publisher()
click to toggle source
The {Publisher} used to send the unsubscribe message @api private
# File lib/attention/subscriber.rb, line 55 def publisher @publisher ||= Publisher.new end
subscribe(&callback)
click to toggle source
Sets up the Redis pub/sub subscription @yield The code to execute on a published event @raise [AlreadySubscribedError] If the subscriber is already subscribed
# File lib/attention/subscriber.rb, line 37 def subscribe(&callback) raise AlreadySubscribedError.new if @thread @thread = Thread.new do redis.subscribe(channel) do |on| on.message do |channel, payload| data = JSON.parse(payload) rescue payload if data == 'unsubscribe' redis.unsubscribe else callback.call channel, data end end end end end
unsubscribe()
click to toggle source
Unsubscribes from the channel
# File lib/attention/subscriber.rb, line 60 def unsubscribe publisher.publish channel, 'unsubscribe' @thread.kill @thread = nil end