Class: BoltRb::Router

Inherits:
Object
  • Object
show all
Defined in:
lib/bolt_rb/router.rb

Overview

Router maintains a registry of handlers and routes incoming payloads to the appropriate handlers based on their matching criteria.

The router acts as the central dispatch mechanism for Bolt applications, collecting registered handlers and determining which ones should process a given Slack payload.

Examples:

Basic usage

router = BoltRb::Router.new

router.register(MyMessageHandler)
router.register(MyCommandHandler)

handlers = router.route(payload)
handlers.each { |h| h.new(context).call }

Using the global router

BoltRb.router.register(MyHandler)
BoltRb.router.route(payload)

Instance Method Summary collapse

Constructor Details

#initializeRouter

Creates a new Router instance with an empty handler registry



25
26
27
# File 'lib/bolt_rb/router.rb', line 25

def initialize
  @handlers = []
end

Instance Method Details

#clearvoid

This method returns an undefined value.

Removes all registered handlers

Useful for testing or reconfiguration scenarios.



71
72
73
# File 'lib/bolt_rb/router.rb', line 71

def clear
  @handlers.clear
end

#handler_countInteger

Returns the number of registered handlers

Returns:

  • (Integer)

    The count of registered handlers



62
63
64
# File 'lib/bolt_rb/router.rb', line 62

def handler_count
  @handlers.length
end

#register(handler_class) ⇒ void

This method returns an undefined value.

Registers a handler class with the router

The handler class should respond to .matches?(payload) to determine if it should process a given payload. Duplicate registrations are ignored.

Examples:

router.register(MyMessageHandler)

Parameters:

  • handler_class (Class)

    A handler class (EventHandler, CommandHandler, etc.)



39
40
41
# File 'lib/bolt_rb/router.rb', line 39

def register(handler_class)
  @handlers << handler_class unless @handlers.include?(handler_class)
end

#route(payload) ⇒ Array<Class>

Routes a payload to all matching handlers

Iterates through all registered handlers and returns those whose .matches?(payload) method returns true.

Examples:

payload = { 'event' => { 'type' => 'message', 'text' => 'hello' } }
handlers = router.route(payload)
# => [MessageHandler, HelloHandler]

Parameters:

  • payload (Hash)

    The incoming Slack payload

Returns:

  • (Array<Class>)

    Array of handler classes that match the payload



55
56
57
# File 'lib/bolt_rb/router.rb', line 55

def route(payload)
  @handlers.select { |handler| handler.matches?(payload) }
end