lib/em-synchrony.rb in em-synchrony-1.0.2 vs lib/em-synchrony.rb in em-synchrony-1.0.3

- old
+ new

@@ -16,18 +16,33 @@ require "em-synchrony/keyboard" require "em-synchrony/iterator" if EventMachine::VERSION > '0.12.10' module EventMachine - # A convenience method for wrapping EM.run body within + # A convenience method for wrapping a given block within # a Ruby Fiber such that async operations can be transparently # paused and resumed based on IO scheduling. - def self.synchrony(blk=nil, tail=nil, &block) - blk ||= block - context = Proc.new { Fiber.new { blk.call }.resume } + # It detects whether EM is running or not. + def self.synchrony(blk=nil, tail=nil) + # EM already running. + if reactor_running? + if block_given? + Fiber.new { yield }.resume + else + Fiber.new { blk.call }.resume + end + tail && add_shutdown_hook(tail) - self.run(context, tail) + # EM not running. + else + if block_given? + run(nil, tail) { Fiber.new { yield }.resume } + else + run(Proc.new { Fiber.new { blk.call }.resume }, tail) + end + + end end module Synchrony # sync is a close relative to inlineCallbacks from Twisted (Python) @@ -95,9 +110,25 @@ # Fiber-aware EM.next_tick convenience function # def self.next_tick(&blk) EM.next_tick { Fiber.new { blk.call }.resume } + end + + # Fiber-aware EM.defer + # + def self.defer op = nil, &blk + fiber = Fiber.current + EM.defer(op || blk, lambda{ |result| fiber.resume(result) }) + Fiber.yield + end + + # Fiber-aware EM.system + # + def self.system cmd, *args + fiber = Fiber.current + EM.system(cmd, *args){ |out, status| fiber.resume( [out, status] ) } + Fiber.yield end # Routes to EM::Synchrony::Keyboard # def self.gets