rails 4 live streaming redis pubsub

Ruby code posted
created at 06 Nov 03:26

Edit | Back
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
require 'reloader/sse'

class BrowserController < ApplicationController
  include ActionController::Live

  def index
    # SSE expects the `text/event-stream` content type
    response.headers['Content-Type'] = 'text/event-stream'

    sse = Reloader::SSE.new(response.stream)

    begin
      $redis.subscribe('browser') do |on|
        on.message do |channel, msg|
          sse.write(msg, :event => 'refresh')
        end
      end
    rescue IOError
      # When the client disconnects, we'll get an IOError on write
    ensure
      sse.close
    end
  end
end
591 Bytes in 3 ms with coderay