Created
October 12, 2012 14:28
-
-
Save jmorton/3879459 to your computer and use it in GitHub Desktop.
Notifying with EventSource, Faye, EventMachine
This file contains 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
require 'faye/websocket' | |
# Configuration: | |
# | |
# With rackup | |
# map '/notifier' do | |
# run Notifier.new | |
# end | |
# | |
# With Rails, add this to config/routes.rb | |
# mount Notifier.new => "/notifier", as: "notifier" | |
# | |
# Usage: | |
# Notifier::Channel.push 'ahoy' | |
# | |
class Notifier | |
Channel = EventMachine::Channel.new | |
def call(env) | |
if Faye::EventSource.eventsource?(env) | |
stream = Faye::EventSource.new(env) | |
sid = Channel.subscribe do |msg| | |
stream.send(msg) | |
end | |
stream.onclose do | |
Channel.unsubscribe(sid) | |
end | |
stream.rack_response | |
else | |
[406, {}, ""] | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment