Class: SpecForge::Forge::Callbacks

Inherits:
Object
  • Object
show all
Defined in:
lib/spec_forge/forge/callbacks.rb

Overview

Manages registered callbacks that can be invoked from blueprints

Callbacks are Ruby blocks registered in forge_helper.rb that can be called during step execution using the call: attribute.

Instance Method Summary collapse

Constructor Details

#initializeCallbacks

Creates a new empty callback registry



17
18
19
# File 'lib/spec_forge/forge/callbacks.rb', line 17

def initialize
  @callbacks = {}
end

Instance Method Details

#register(name) { ... } ⇒ Object

Registers a callback with the given name

Parameters:

  • name (String, Symbol)

    The name to register the callback under

Yields:

  • The block to execute when the callback is invoked

Raises:

  • (ArgumentError)

    If no block is provided



30
31
32
33
34
35
36
37
38
# File 'lib/spec_forge/forge/callbacks.rb', line 30

def register(name, &block)
  raise ArgumentError, "A block must be provided" unless block.is_a?(Proc)

  if registered?(name)
    warn("Callback #{name.in_quotes} is already registered. It will be overwritten")
  end

  @callbacks[name.to_sym] = block
end

#registered?(name) ⇒ Boolean

Checks if a callback with the given name has been registered

Parameters:

  • name (String, Symbol)

    The callback name to check

Returns:

  • (Boolean)

    Whether the callback is registered



47
48
49
# File 'lib/spec_forge/forge/callbacks.rb', line 47

def registered?(name)
  @callbacks.key?(name.to_sym)
end

#run(name, context = nil, arguments = []) ⇒ Object

Executes a registered callback by name

Parameters:

  • name (String, Symbol)

    The callback name to execute

  • context (Forge::Context, nil) (defaults to: nil)

    The current execution context

  • arguments (Array, Hash) (defaults to: [])

    Arguments to pass to the callback

Returns:

  • (Object)

    The return value of the callback

Raises:



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/spec_forge/forge/callbacks.rb', line 62

def run(name, context = nil, arguments = [])
  raise Error::UndefinedCallbackError.new(name, @callbacks.keys) unless registered?(name)

  callback = @callbacks[name.to_sym]

  # No arguments? Just call
  return callback.call if callback.arity == 0
  return callback.call(context) if callback.arity == 1

  case arguments
  when Array
    callback.call(context, *arguments)
  when Hash
    callback.call(context, **arguments)
  end
end