Sha256: 0498906b5d753374005658d25ad379a9eacbe4580783ac7a03ab508075c7b8a1

Contents?: true

Size: 954 Bytes

Versions: 1

Compression:

Stored size: 954 Bytes

Contents

require 'fiber'

begin
  require 'eventmachine'
rescue => e
  raise 'Abstractivator::FiberDefer requires eventmachine but it is unavailable.'
end

module Abstractivator
  module FiberDefer
    ROOT_FIBER = Fiber.current

    def with_fiber_defer(&block)
      raise 'this method requires an eventmachine reactor to be running' unless EM.reactor_running?
      Fiber.new{block.call}.resume if block
    end

    def fiber_defer(&action)
      f = Fiber.current
      raise 'fiber_defer must be passed an action to defer (the block)' unless action
      raise 'fiber_defer must be called within a with_fiber_defer block' if f == ROOT_FIBER

      safe_action = proc do
        begin
          [action.call, nil]
        rescue Exception => e
          [nil, e]
        end
      end

      EM.defer(safe_action, proc { |result, error| f.resume([result, error]) })
      result, error = Fiber.yield
      raise error if error
      result
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
abstractivator-0.2.0 lib/abstractivator/fiber_defer.rb