Created
May 2, 2012 03:52
-
-
Save nhocki/2573468 to your computer and use it in GitHub Desktop.
Sinatra stream example
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 '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