Skip to content

Instantly share code, notes, and snippets.

@Dremora
Created November 22, 2010 00:00
Show Gist options
  • Save Dremora/709312 to your computer and use it in GitHub Desktop.
Save Dremora/709312 to your computer and use it in GitHub Desktop.
EventStream
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