class Hooks::Hook(T)

Overview

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))

Defined in:

hooks/hook.cr

Instance Method Summary

Instance Method Detail

def add(handler : Handler(T)) : String #

Registers a new handler by appending it to the queue


[View source]
def handlers : Array(HandlerPair(T)) #

[View source]
def handlers=(handlers : Array(HandlerPair(T))) #

[View source]
def pre_add(handler : Handler(T)) : String #

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


[View source]
def remove(id : String) #

Removes a handler by its ID


[View source]
def remove_all #

Removes all handlers


[View source]
def 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.


[View source]
def 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.


[View source]
def 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.


[View source]
def 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.


[View source]