Module: FiberHook

Defined in:
lib/fiber_hook.rb,
lib/fiber_hook/version.rb

Overview

Allows you to hook fiber creation so you can call a method from the parent fiber immediately before any child fiber is created, return a value, and then call another method from inside the child fiber the first time the fiber is resumed, passing in the value that was returned from the first method.

Defined Under Namespace

Modules: ClassMethods Classes: Error

Constant Summary collapse

VERSION =
"0.1.0"

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.hooksObject (readonly)

Returns the value of attribute hooks.



15
16
17
# File 'lib/fiber_hook.rb', line 15

def hooks
  @hooks
end

Class Method Details

.add(new: nil, resume: nil) ⇒ Integer

Add a hook and return its id.

Parameters:

  • new (Proc) (defaults to: nil)

    Method to be called in parent fiber context when Fiber.new is called. Takes no params. Its return value will be passed into resume.

  • resume (Proc) (defaults to: nil)

    Method to be called in child fiber’s context when Fiber#resume is called for the first time. Takes a single param: the value returned by new.

Returns:

  • (Integer)

    The id of the newly-created hook. Can be passed in to has? or remove.



28
29
30
31
32
# File 'lib/fiber_hook.rb', line 28

def self.add(new: nil, resume: nil)
  @prev_id += 1
  @hooks[@prev_id] = { new: new, resume: resume }
  @prev_id
end

.has?(hook_id) ⇒ Boolean

Is this hook id valid?

Returns:

  • (Boolean)


35
36
37
# File 'lib/fiber_hook.rb', line 35

def self.has?(hook_id)
  @hooks.key?(hook_id)
end

.remove(hook_id) ⇒ Object

Remove a hook by its id. Afterward, newly-created fibers won’t have this hook.

Raises:



40
41
42
43
# File 'lib/fiber_hook.rb', line 40

def self.remove(hook_id)
  value = @hooks.delete(hook_id)
  raise Error, "Hook #{hook_id} not found" unless value
end