Skip to content

Instantly share code, notes, and snippets.

@thedanielhanke
Created January 29, 2018 22:10
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 thedanielhanke/39fedc944328b602ecc6645100759e20 to your computer and use it in GitHub Desktop.
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.
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
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
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