Created
January 29, 2018 22:10
-
-
Save thedanielhanke/39fedc944328b602ecc6645100759e20 to your computer and use it in GitHub Desktop.
Example of how to do a live streaming Rails 4 model and controller using postgresql pubsub. + event module for formatting SSE.
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
class Evacuation < ActiveRecord::Base | |
def self.notify_person_found | |
connection.execute "NOTIFY evac, #{connection.quote 'found person'}" | |
end | |
def self.on_person_found | |
begin | |
connection.execute "LISTEN evac" | |
loop do | |
connection.raw_connection.wait_for_notify do |event, pid, message| | |
yield message | |
end | |
end | |
ensure | |
connection.execute "UNLISTEN evac" | |
end | |
end | |
end |
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 'json' | |
module Eventer | |
class SSE | |
def initialize io | |
@io = io | |
end | |
def write object, options = {} | |
options.each do |k,v| | |
@io.write "#{k}: #{v}\n" | |
end | |
@io.write "data: #{JSON.dump(object)}\n\n" | |
end | |
def close | |
@io.close | |
end | |
end | |
end |
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 'eventer/sse' | |
class TrackingController < ApplicationController | |
include ActionController::Live | |
def listen | |
response.headers['Content-Type'] = 'text/event-stream' | |
sse = Eventer::SSE.new(response.stream) | |
begin | |
Evacuation.on_person_found do | |
sse.write({ :time => Time.now }, {event: 'found'}) | |
sleep 1 | |
end | |
rescue IOError | |
# Client disconnect | |
ensure | |
sse.close | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment