Module: EventMachine::SyncDefer

Defined in:
lib/eventmachine/sync-defer.rb

Class Method Summary collapse

Class Method Details

.defer(*funcs, &block) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/eventmachine/sync-defer.rb', line 7

def defer *funcs, &block
  fiber = Fiber.current
  funcs << block if block_given?
  if    funcs.empty?
    return
  elsif funcs.size == 1
    defer_one(fiber, funcs.first)
  else
    defer_multi(fiber, funcs)
  end
  result, exception = Fiber.yield
  if exception
    raise exception
  else
    result
  end
end

.defer_multi(fiber, funcs) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/eventmachine/sync-defer.rb', line 37

def defer_multi fiber, funcs
  results, exception = {}, nil
  funcs.each.with_index do |func, index|
    EventMachine.defer(
      lambda{
        begin
          func.call
        rescue Exception => e
          exception = e
        end
      },
      lambda{ |result|
        if exception
          fiber.resume(nil, exception) if fiber.alive?
        else
          results[index] = result
          fiber.resume(results.sort.map(&:last), nil) if
            results.size == funcs.size && fiber.alive?
        end
      })
  end
end

.defer_one(fiber, func) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/eventmachine/sync-defer.rb', line 25

def defer_one fiber, func
  exception = nil
  EventMachine.defer(lambda{
                       begin
                         func.call
                       rescue Exception => e
                         exception = e
                       end
                     },
                     lambda{ |result| fiber.resume(result, exception)})
end