Module: FiberHook::ClassMethods

Defined in:
lib/fiber_hook.rb

Overview

Class methods that will be added to Fiber.

Instance Method Summary collapse

Instance Method Details

#hook(**options) ⇒ Object

See Also:



63
64
65
# File 'lib/fiber_hook.rb', line 63

def hook(**options)
  FiberHook.add(**options)
end

#hook?(hook_id) ⇒ Boolean

Returns:

  • (Boolean)

See Also:



73
74
75
# File 'lib/fiber_hook.rb', line 73

def hook?(hook_id)
  FiberHook.has?(hook_id)
end

#new(*args, &block) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/fiber_hook.rb', line 47

def new(*args, &block)
  # In Fiber.new, call the :new methods of all the hooks. Save the results.
  values = FiberHook.hooks.transform_values { |hook| hook[:new]&.call }

  fiber_proc = proc do |*block_args|
    # In Fiber.resume, call the :resume methods of all the hooks.
    # Pass in the values returned by the :new methods.
    FiberHook.hooks.each { |id, hook| hook[:resume]&.call(values[id]) }
    # Then call the original fiber block.
    block.call(*block_args)
  end

  super(*args, &fiber_proc)
end

#unhook(hook_id) ⇒ Object

See Also:



68
69
70
# File 'lib/fiber_hook.rb', line 68

def unhook(hook_id)
  FiberHook.remove(hook_id)
end