class

Hooks::Hook(T)

Inherits Reference < Object

Thread-safe event handling system

# Set up hooks with ordered handlers
hook = Hook(Int32).new
hook.add(Handler(Int32).new { |n| puts "First: #{n}" })
hook.pre_add(Handler(Int32).new { |n| puts "Before: #{n}" })

# Add one-off handlers during trigger
hook.trigger(42,
  Handler(Int32).new { |n| puts "One-time: #{n}" },
  Handler(Int32).new { |n| raise StopPropagation.new } # Stop processing
)

# Handle errors without stopping
result = hook.trigger_with_continuation(42)
puts result if result.is_a?(Array(Exception))

Instance methods

add(handler : Handler(T)) : String

Registers a new handler by appending it to the queue

Source
handlers
Source
handlers=(handlers : Array(HandlerPair(T)))
Source
pre_add(handler : Handler(T)) : String

Registers a new handler to the hook by prepending it to the existing queue

Source
remove(id : String)

Removes a handler by its ID

Source
remove_all

Removes all handlers

Source
trigger(data : T, one_off_handlers : Array(Handler(T)) = [] of Handler(T)) : Nil | Exception

Triggers all registered hook handlers sequentially with data as an argument. It also supports adding temporary, one-off handlers for a single trigger execution. Execution halts when either StopPropagation is raised or any other exception occurs.

Source
trigger(data : T, *one_off_handlers : Handler(T)) : Nil | Exception

Triggers all registered hook handlers sequentially with data as an argument. It also supports adding temporary, one-off handlers for a single trigger execution. Execution halts when either StopPropagation is raised or any other exception occurs.

Source
trigger_with_continuation(data : T, one_off_handlers : Array(Handler(T)) = [] of Handler(T)) : Nil | Array(Exception)

Triggers all registered hook handlers sequentially with data as an argument. This variant continues execution after encountering exceptions, except for StopPropagation, which halts further execution.

Source
trigger_with_continuation(data : T, *one_off_handlers : Handler(T)) : Nil | Array(Exception)

Triggers all registered hook handlers sequentially with data as an argument. This variant continues execution after encountering exceptions, except for StopPropagation, which halts further execution.

Source