Created
April 14, 2012 06:27
-
-
Save eggie5/2382465 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #** | |
| #* 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