Module: Lennarb::Hooks

Defined in:
lib/lennarb/hooks.rb

Overview

Note:
  • Hooks are executed in the order they are added.

  • The context of the hook is the object that calls the route handler.

  • Hooks can modify the request and response objects.

  • Hooks can be used to implement middleware-like functionality.

  • Hooks are not thread-safe. Use with caution in multi-threaded environments.

Provides hook functionality for Lennarb applications. Hooks execute code before and after route handlers.

Examples:

Hooks.add(MyApp, :before) do |req, res|
  res.headers["X-My-Header"] = "MyValue"
end
Hooks.add(MyApp, :after) do |req, res|
  res.body << "Goodbye!"
end

Constant Summary collapse

TYPES =

Valid hook types

[:before, :after].freeze

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.app_hooksHash (readonly)

Get the hooks hash

Returns:

  • (Hash)

    The hooks hash with app classes as keys



30
31
32
# File 'lib/lennarb/hooks.rb', line 30

def app_hooks
  @app_hooks
end

Class Method Details

.add(app_class, type, &block) ⇒ Array

Add a hook for an app class

Parameters:

  • app_class (Class)

    The application class

  • type (Symbol)

    The hook type (:before or :after)

  • block (Proc)

    The hook block

Returns:

  • (Array)

    The hooks array for the given type

Raises:

  • (ArgumentError)


46
47
48
49
50
51
52
# File 'lib/lennarb/hooks.rb', line 46

def add(app_class, type, &block)
  raise ArgumentError, "Invalid hook type: #{type}" unless TYPES.include?(type)

  hooks = self.for(app_class)
  hooks[type] << block if block_given?
  hooks[type]
end

.execute(context, app_class, type, req, res) ⇒ void

This method returns an undefined value.

Execute hooks of a given type

Parameters:

  • context (Object)

    The execution context

  • app_class (Class)

    The application class

  • type (Symbol)

    The hook type to execute

  • req (Request)

    The request object

  • res (Response)

    The response object



62
63
64
65
66
67
68
# File 'lib/lennarb/hooks.rb', line 62

def execute(context, app_class, type, req, res)
  hooks = self.for(app_class)[type]

  hooks.each do |hook|
    context.instance_exec(req, res, &hook)
  end
end

.for(app_class) ⇒ Hash

Get the hooks for an app class

Parameters:

  • app_class (Class)

    The application class

Returns:

  • (Hash)

    The hooks hash with :before and :after keys



36
37
38
# File 'lib/lennarb/hooks.rb', line 36

def for(app_class)
  app_hooks[app_class] ||= {before: [], after: []}
end