From 65bac923dc0d629ec102d6d33a95a142ec7e8995 Mon Sep 17 00:00:00 2001 From: Damian Janowski Date: Wed, 20 Oct 2010 20:59:14 -0300 Subject: [PATCH] Prettify pub/sub example after non-issue #62. --- examples/pubsub.rb | 48 ++++++++++++++++++++++++++-------------------- 1 file changed, 27 insertions(+), 21 deletions(-) diff --git a/examples/pubsub.rb b/examples/pubsub.rb index 8b5429c67..6cf17aeec 100644 --- a/examples/pubsub.rb +++ b/examples/pubsub.rb @@ -1,25 +1,31 @@ -require 'rubygems' -require 'redis' - -puts "To play with this example use redis-cli from another terminal, like this:" -puts " ./redis-cli publish one hello" -puts "Finally force the example to exit sending the 'exit' message with" -puts " ./redis-cli publish two exit" -puts "" - -@redis = Redis.new(:timeout => 0) - -@redis.subscribe('one','two') do |on| - on.subscribe {|klass, num_subs| puts "Subscribed to #{klass} (#{num_subs} subscriptions)" } - on.message do |klass, msg| - puts "#{klass} received: #{msg}" - if msg == 'exit' - @redis.unsubscribe - end - end - on.unsubscribe {|klass, num_subs| puts "Unsubscribed to #{klass} (#{num_subs} subscriptions)" } -end +require "redis" + +puts <<-EOS +To play with this example use redis-cli from another terminal, like this: + + $ redis-cli publish one hello + +Finally force the example to exit sending the 'exit' message with: + + $ redis-cli publish two exit +EOS +redis = Redis.connect +trap(:INT) { puts; exit } +redis.subscribe(:one, :two) do |on| + on.subscribe do |channel, subscriptions| + puts "Subscribed to ##{channel} (#{subscriptions} subscriptions)" + end + + on.message do |channel, message| + puts "##{klass}: #{message}" + redis.unsubscribe if message == "exit" + end + + on.unsubscribe do |channel, subscriptions| + puts "Unsubscribed from ##{klass} (#{subscriptions} subscriptions)" + end +end