Skip to content

Instantly share code, notes, and snippets.

@nhocki
Created May 2, 2012 03:52
Show Gist options
  • Save nhocki/2573468 to your computer and use it in GitHub Desktop.
Save nhocki/2573468 to your computer and use it in GitHub Desktop.
Sinatra stream example
require 'sinatra/base'
class Stream < Sinatra::Base
before do
content_type :txt
end
connections = []
get '/consume/?' do
stream(:keep_open) do |out|
connections << out
out.callback { connections.delete(out) }
out.errback do
logger.warn 'OMG! Something went wrong!'
connections.delete(out)
end
end
end
get '/broadcast/:message' do
connections.each do |out|
out << "#{Time.now}: #{params[:message]}" << "\n"
end
"Sent #{params[:message]} to all clients"
end
get '/' do
stream do |out|
out << "It's gonna be legen -\n"
sleep 0.5
out << " (wait for it) \n"
sleep 1
out << "- dary!\n"
end
end
end
run Stream
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment