Skip to content

Instantly share code, notes, and snippets.

@pricees
Created November 12, 2012 21:50
Show Gist options
  • Save pricees/4062164 to your computer and use it in GitHub Desktop.
Save pricees/4062164 to your computer and use it in GitHub Desktop.
Redis Pubsub Subscriber Class
# Public: Subscriber class for digesting conn messages
#
# channel - Channel to subscribe to
# block - Block for digesting message (opt)
#
# Examples
#
# # With a block!
# Subscriber.new("test").start
# #=> "Subscribed to #test"
# #=> "#test: Hello World"
#
# # With a block!
# r = Subscriber.new("test") do |channel, msg|
# puts "Block Msg from ##{channel}: #{msg}"
# end
# r.start
# #=> "Subscribed to #test"
# #=> "Msg from #test: Hello World"
class Subscriber
def conn
@conn ||= RDB.conn
end
def initialize(channel, &block)
@channel = channel
@block = block if block_given?
end
def start
conn.subscribe(@channel) do |on|
on.subscribe do |channel, subscriptions|
puts "Subscribed to ##{channel}"
end
on.message do |channel, message|
if message == "exit"
conn.unsubscribe
else
unless @block && @block[channel, message]
puts "##{channel}: #{message}"
end
end
end
on.unsubscribe do |channel, subscriptions|
puts "Unsubscribed from ##{channel}"
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment