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.
Constant Summary collapse
- TYPES =
Valid hook types
[:before, :after].freeze
Class Attribute Summary collapse
-
.app_hooks ⇒ Hash
readonly
Get the hooks hash.
Class Method Summary collapse
-
.add(app_class, type, &block) ⇒ Array
Add a hook for an app class.
-
.execute(context, app_class, type, req, res) ⇒ void
Execute hooks of a given type.
-
.for(app_class) ⇒ Hash
Get the hooks for an app class.
Class Attribute Details
.app_hooks ⇒ Hash (readonly)
Get the hooks hash
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
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
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
36 37 38 |
# File 'lib/lennarb/hooks.rb', line 36 def for(app_class) app_hooks[app_class] ||= {before: [], after: []} end |