Skip to content

Instantly share code, notes, and snippets.

@bsa7
Forked from lexmag/application.js
Created June 29, 2014 11:55
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 bsa7/35d13910fdad3f1040b6 to your computer and use it in GitHub Desktop.
Save bsa7/35d13910fdad3f1040b6 to your computer and use it in GitHub Desktop.
Rails 3,4 streaming
//= require jquery
//= require jquery_ujs
$(function() {
var source = new EventSource('/stream');
source.addEventListener('counter', function(e) {
$('body').after(e.data + '<br />');
});
});
class PostsController < ApplicationController
# ...
def stream
response.headers.delete('Content-Length')
response.headers['Cache-Control'] = 'no-cache'
response.headers['Content-Type'] = 'text/event-stream'
self.response_body = Enumerator.new do |y|
loop do
if (Time.current.sec % 5).zero?
y << "event: counter\n"
y << "data: 5 seconds passed\n\n"
end
sleep 1
end
end
end
# The new approach
# include ActionController::Live
def stream
response.headers['Content-Type'] = 'text/event-stream'
begin
loop do
if (Time.current.sec % 5).zero?
response.stream.write("event: counter\n")
response.stream.write("data: 5 seconds passed\n\n")
end
sleep 1
end
rescue IOError
# Catch when the client disconnects
ensure
response.stream.close
end
end
# ...
end
- close stream
- IE has not server-sent events
- preload_frameworks & allow_concurrency options in development
- Puma, Thin, Rainbow! servers
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment