Permalink
Browse files

send browser events on new orders

  • Loading branch information...
1 parent f16c601 commit 422cb20b997db4d91c18372ddc2d16f013182516 @rkh rkh committed Jan 19, 2012
@@ -72,5 +72,13 @@ $.fn.donations = ()->
new Donations(this, $('.pagination', this))
$(document).ready ->
- $('#donations').donations() if $('#donations').length > 0
+ if $('#donations').length > 0
+ $('#donations').donations()
+ if EventSource?
+ src = new EventSource('/orders.es')
+ src.onmessage = (e) ->
+ payload = JSON.parse e.data
+ order = payload.order
+ user = order.user
+ Notifier.notify "We've got another one!", "#{user.name} just donated $#{order.total}!", user.gravatar_url, 2000

Large diffs are not rendered by default.

Oops, something went wrong.
@@ -0,0 +1,5 @@
+class OrderObserver < ActiveRecord::Observer
+ def after_create(order)
+ OrderStream.send_json(order: order.as_json)
+ end
+end
View
@@ -1,4 +1,7 @@
# This file is used by Rack-based servers to start the application.
require ::File.expand_path('../config/environment', __FILE__)
-run Travis::Application
+require 'order_stream'
+
+map('/') { run Travis::Application }
+map('/orders.es') { run OrderStream }
View
@@ -50,6 +50,7 @@ class Application < Rails::Application
config.action_mailer.default_url_options = { :host => 'support.travis-ci.org' }
+ config.active_record.observers = :order_observer
config.threadsafe!
end
end
View
@@ -0,0 +1,43 @@
+require 'eventmachine'
+
+class OrderStream
+ @streams ||= []
+
+ def self.call(env)
+ stream = new
+ @streams << stream
+ env['async.close'].callback { @streams.delete(stream) }
+ EM.next_tick { env['async.callback'].call [200, {'Content-Type' => 'text/event-stream'}, stream] }
+ throw :async
+ end
+
+ def self.send_json(data)
+ send_message(data.as_json.to_json)
+ @streams.each { |s| s << data.as_json.to_json }
+ end
+
+ def self.send_message(data)
+ data.split(/\n/).each { |l| send_raw("data: #{l}\n") }
+ send_raw("\n")
+ end
+
+ def self.send_raw(data)
+ @streams.each { |s| s << data.to_s }
+ end
+
+ include EventMachine::Deferrable
+
+ def <<(data)
+ @body_callback.call(data)
+ end
+
+ def initialize
+ @body_callback = proc { |_| }
+ end
+
+ def each(&block)
+ @body_callback = block
+ end
+
+ #EventMachine.schedule { EventMachine::PeriodicTimer.new(10) { send_raw "\0" } }
+end
@@ -0,0 +1,7 @@
+require 'test_helper'
+
+class OrderObserverTest < ActiveSupport::TestCase
+ # test "the truth" do
+ # assert true
+ # end
+end

0 comments on commit 422cb20

Please sign in to comment.