Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

add EM::Synchrony.sync for inline fiber sync (aka, inlineCallbacks in

Python)
  • Loading branch information...
commit ce3fefa2126be07e8717bfcad04b9be0fb849c0c 1 parent 848b260
Ilya Grigorik authored
Showing with 63 additions and 1 deletion.
  1. +26 −1 lib/em-synchrony.rb
  2. +37 −0 spec/inlinesync_spec.rb
27 lib/em-synchrony.rb
View
@@ -24,4 +24,29 @@ def self.synchrony(blk=nil, tail=nil, &block)
self.run(context, tail)
end
-end
+ module Synchrony
+
+ # sync is a close relative to inclineCallbacks from Twisted (Python)
+ #
+ # Synchrony.sync allows you to write sequential code while using asynchronous
+ # or callback-based methods under the hood. Example:
+ #
+ # result = EM::Synchrony.sync EventMachine::HttpRequest.new(URL).get
+ # p result.response
+ #
+ # As long as the asynchronous function returns a Deferrable object, which
+ # has a "callback" and an "errback", the sync methond will automatically
Raoul Felix
rfelix added a note

Typo: methond to method

Ilya Grigorik Owner

Woops, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+ # yield and automatically resume your code (via Fibers) when the call
+ # either succeeds or fails. You do not need to patch or modify the
+ # Deferrable object, simply pass it to EM::Synchrony.sync
+ #
+ def self.sync(df)
+ f = Fiber.current
+ df.callback { |r| f.resume(r) }
+ df.errback { |r| f.resume(r) }
+
+ Fiber.yield
+ end
+ end
+
+end
37 spec/inlinesync_spec.rb
View
@@ -0,0 +1,37 @@
+require "spec/helper/all"
+require "em-synchrony/iterator"
+
+describe EventMachine::Synchrony do
+
+ URL = "http://localhost:8081/"
+ DELAY = 0.01
+
+ it "should allow inline callbacks for Deferrable object" do
+ EM.synchrony do
+ s = StubServer.new("HTTP/1.0 200 OK\r\nConnection: close\r\n\r\nFoo", DELAY)
+
+ result = EM::Synchrony.sync EventMachine::HttpRequest.new(URL).aget
+ result.response.should match(/Foo/)
+
+ EM.stop
+ end
+ end
+
+ it "should inline errback/callback cases" do
+ EM.synchrony do
+ class E
+ include EventMachine::Deferrable
+ def run
+ EM.add_timer(0.01) {fail("uh oh!")}
+ self
+ end
+ end
+
+ result = EM::Synchrony.sync E.new.run
+ result.should match(/uh oh!/)
+
+ EM.stop
+ end
+ end
+
+end
Raoul Felix

Typo: methond to method

Ilya Grigorik

Woops, thanks!

Please sign in to comment.
Something went wrong with that request. Please try again.