Skip to content

Instantly share code, notes, and snippets.

@jamiehodge
Last active November 28, 2017 23:23
Show Gist options
  • Save jamiehodge/5676442 to your computer and use it in GitHub Desktop.
Save jamiehodge/5676442 to your computer and use it in GitHub Desktop.
Server Side Events, Sequel and Postgres LISTEN/NOTIFY
require 'sequel'
DB ||= Sequel.connect ENV['DATABASE_URL']
class Resource < Sequel::Model
include Sequel.inflections
def after_save
db.notify channel
end
def listen
db.listen channel, loop: true do |channel, pid, payload|
yield channel
end
end
def channel
[self.class.table_name, id].join '_'
end
end
require 'sinatra'
require 'json'
require_relative 'resource'
configure do
mime_type :event_stream, 'text/event-stream'
end
get '/:id/stream', provides: :event_stream do
stream do |out|
resource.listen do |channel|
out << message(event: channel, data: resource.reload)
break if out.closed?
end
end
end
def resource
@resource ||= Resource[params[:id]]
end
def message(event:, data:)
"event: %s\ndata: %s\\n" % [event, data.to_json]
end
require 'securerandom'
require_relative 'resource'
loop do
Resource[2].update title: SecureRandom.hex
sleep 5
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment