Created
October 14, 2012 14:52
-
-
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)
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 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() | |
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
# 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 |
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 PusherController < ApplicationController | |
def index | |
render json: Array(CACHED.get("pusher:#{channel}:#{event}")) | |
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
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