Created
November 22, 2010 00:00
-
-
Save Dremora/709312 to your computer and use it in GitHub Desktop.
EventStream
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
require 'sinatra' | |
require 'eventmachine' | |
class EventStream | |
include EventMachine::Deferrable | |
def initialize(channel, &block) | |
@channel = channel | |
@block = block | |
end | |
def self.create(channel, request, &block) | |
EventMachine.next_tick do | |
request.env['async.callback'].call [ | |
200, {'Content-Type' => 'text/event-stream'}, | |
EventStream.new(channel, &block) ] | |
end | |
[-1, {}, []] | |
end | |
def each | |
@sid = @channel.subscribe do |event| | |
@block.call(event).each do |key, value| | |
yield "#{key}: #{value}\n" | |
end | |
yield "\n" | |
end | |
errback do | |
@channel.unsubscribe @sid | |
end | |
end | |
end | |
events_channel = EM::Channel.new | |
get '/events' do | |
EventStream.create events_channel, request do |event| | |
{ :id => event } | |
end | |
end | |
post '/events' do | |
events_channel << params[:event] | |
nil | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment