Skip to content

Instantly share code, notes, and snippets.

@calvincorreli
Created October 14, 2012 14:52
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 calvincorreli/3888823 to your computer and use it in GitHub Desktop.
Save calvincorreli/3888823 to your computer and use it in GitHub Desktop.
Simple wrapper library for Pusher with the ability to replay recent events (< 2 minutes ago)
class window.ZenPusher
@pusher: null
@channel: []
constructor: ->
setupPusher: _.once ->
@pusher = new Pusher($('body').data('pusher-key'))
channel: (channel) ->
@.setupPusher()
@channel[channel] ||= @pusher.subscribe(channel)
bind: (channel, event, callback) ->
@.channel(channel).bind(event, callback)
# Also fetch any events that we may have just missed
@.fetchEvents channel, event, callback
bindAll: (channel, bindings) ->
for event, callback of bindings
@.bind(channel, event, callback)
fetchEvents: (channel, event, callback) ->
$.ajax
url: "/pusher/#{channel}/#{event}/"
type: 'POST'
success: (events, status, xhr) ->
callback.call(null, data) for data in events
window.pusher = new ZenPusher()
# Mixin to ActiveRecord
module Zen
module Pusher
def notify_browser(event, data = {})
channel = "#{self.class.base_class.name.demodulize.dasherize}-#{id}"
Pusher[channel].trigger(event, data)
CACHED.set("pusher:#{channel}:#{event}", data, 2.minutes.to_i)
end
end
end
class PusherController < ApplicationController
def index
render json: Array(CACHED.get("pusher:#{channel}:#{event}"))
end
end
match 'pusher/:channel/:event' => 'pusher#index', as: :pusher_channel_events
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment