Module: SyncDefer

Defined in:
lib/sync-defer.rb

Constant Summary collapse

RootFiber =

assume we would always require ‘rest-core’ in root fiber

Fiber.current

Class Method Summary collapse

Class Method Details

.defer(*args, &block) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/sync-defer.rb', line 19

def defer *args, &block
  if fiber_wrapped?
    if Object.const_defined?(:EventMachine) &&
       EventMachine.reactor_running?
      EventMachine::SyncDefer.defer(*args, &block)

    elsif Object.const_defined?(:Coolio) &&
          Coolio::Loop.default.has_active_watchers?
      Coolio::SyncDefer.defer(*args, &block)

    else
      fallback("No reactor found.", *args, block)
    end

  else
    fallback("Not called inside a fiber.", *args, &block)
  end
end

.fallback(message, *args, &block) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/sync-defer.rb', line 43

def fallback message, *args, &block
  $stderr.puts("SyncDefer: WARN: #{message}")
  $stderr.puts("           Falling back to run the computation directly.")
  $stderr.puts("           Called from: #{caller.first(5).inspect}")
  args << block if block_given?
  if args.size == 1
    args.first.call
  else
    args.map(&:call)
  end
end

.fiber_wrapped?Boolean

Returns:

  • (Boolean)


38
39
40
41
# File 'lib/sync-defer.rb', line 38

def fiber_wrapped?
  # because under a thread, Fiber.current won't return the root fiber
  RootFiber != Fiber.current && Thread.main == Thread.current
end