Class: Docbook::Mirror::HandlerRegistry

Inherits:
Object
  • Object
show all
Defined in:
lib/docbook/mirror/handler_registry.rb

Overview

Registry mapping DocBook element classes to handler methods.

Replaces the closed case/when dispatch in DocbookToMirror with an open registry that supports third-party extension without modifying core classes.

Usage: registry = Docbook::Mirror.default_registry # Add a custom handler for a new element type registry.register(MyCustomElement, ->(el, ctx) { ... })

Defined Under Namespace

Classes: Entry

Instance Method Summary collapse

Constructor Details

#initializeHandlerRegistry

Returns a new instance of HandlerRegistry.



20
21
22
# File 'lib/docbook/mirror/handler_registry.rb', line 20

def initialize
  @handlers = {}
end

Instance Method Details

#entry_for(element) ⇒ Entry?

Find the handler entry for a given DocBook element.

Returns:



45
46
47
# File 'lib/docbook/mirror/handler_registry.rb', line 45

def entry_for(element)
  @handlers[element.class]
end

#handle(element, context:) ⇒ Object

Invoke the handler for a given element. Returns [result, concat_flag] or nil if no handler registered.



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/docbook/mirror/handler_registry.rb', line 56

def handle(element, context:)
  entry = @handlers[element.class]
  return nil unless entry

  kwargs = { context: context }.merge(entry.extra_kwargs || {})

  result = case entry.handler
           when Proc
             entry.handler.call(element, context)
           else
             entry.handler.send(entry.method_name, element, **kwargs)
           end

  [result, entry.concat]
end

#register(element_class, handler, method_name: :call, concat: false, extra_kwargs: {}) ⇒ Object

Register a handler for a DocBook element class.

Parameters:

  • element_class (Class)

    the DocBook element class to handle

  • handler (Module, Class, Proc)

    the handler. If a Module/Class, must respond to the given method_name. If a Proc, called directly.

  • method_name (Symbol) (defaults to: :call)

    method to call on handler (default: :call)

  • concat (Boolean) (defaults to: false)

    if true, handler result is an array to concat into the content array rather than a single item to append

  • extra_kwargs (Hash) (defaults to: {})

    additional keyword arguments to pass to the handler



33
34
35
36
37
38
39
40
41
# File 'lib/docbook/mirror/handler_registry.rb', line 33

def register(element_class, handler, method_name: :call, concat: false,
extra_kwargs: {})
  @handlers[element_class] = Entry.new(
    handler: handler,
    method_name: method_name,
    concat: concat,
    extra_kwargs: extra_kwargs,
  )
end

#registered?(element_class) ⇒ Boolean

Check if a handler is registered for an element class.

Returns:

  • (Boolean)


50
51
52
# File 'lib/docbook/mirror/handler_registry.rb', line 50

def registered?(element_class)
  @handlers.key?(element_class)
end