Skip to content

Instantly share code, notes, and snippets.

@lisovskyvlad
Forked from lexmag/counter.rb
Created November 23, 2015 23:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lisovskyvlad/bc3a9518997e26302ec1 to your computer and use it in GitHub Desktop.
Save lisovskyvlad/bc3a9518997e26302ec1 to your computer and use it in GitHub Desktop.
Terribly simple Sinatra streaming
require 'sinatra'
set server: :thin
get '/' do
erb :welcome
end
get '/stream', provides: 'text/event-stream' do
stream do |out|
loop do
if (Time.now.sec % 5).zero?
out << "event: counter\n"
out << "data: 5 seconds passed\n\n"
end
sleep 1
end
end
end
__END__
@@ layout
<html>
<head>
<title>Terribly simple streaming with Sinatra</title>
<meta charset='utf-8' />
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'></script>
<script>
var source = new EventSource('/stream');
source.addEventListener('counter', function(e) { $('#counter').append(e.data + '<br />') });
</script>
</head>
<body><%= yield %></body>
</html>
@@ welcome
<div id='counter'></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment