Skip to content

Instantly share code, notes, and snippets.

@eggie5
Created April 14, 2012 06:27
Show Gist options
  • Select an option

  • Save eggie5/2382465 to your computer and use it in GitHub Desktop.

Select an option

Save eggie5/2382465 to your computer and use it in GitHub Desktop.
#**
#* Subscribe
#*
#* This is BLOCKING.
#* Listen for a message on a channel.
#*
#* @param array args with channel and message.
#* @return false on fail, array on success.
#*
def subscribe(args)
## Capture User Input
channel = args['channel']
callback = args['callback']
## Fail if missing channel
if !channel
puts "Missing Channel."
return false
end
## Fail if missing callback
if !callback
puts "Missing Callback."
return false
end
## Begin Subscribe
loop do
begin
timetoken = args['timetoken'] ? args['timetoken'] : 0
## Wait for Message
response = self._request([
'subscribe',
@subscribe_key,
channel,
'0',
timetoken.to_s
])
messages = response[0]
args['timetoken'] = response[1]
## If it was a timeout
next if !messages.length
## Run user Callback and Reconnect if user permits.
messages.each do |message|
if !callback.call(message)
return
end
end
rescue Timeout::Error
rescue
sleep(1)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment