Class: Stenotype::ContextHandlers::Collection

Inherits:
Collectible::CollectionBase
  • Object
show all
Defined in:
lib/stenotype/context_handlers/collection.rb

Overview

A class representing a list of available context handlers

Examples:

Complete usage overview

class MyCustomHander
  self.handler_name = :custom_handler

  def as_json(*_args)
    {
      key: :value
    }
  end
end

collection = Stenotype::ContextHandlers::Collection.new
collection.register(MyCustomHandler)

collection.registered?(MyCustomHandler) #=> true
collection.choose(handler_name: :custom_handler) #=> MyCustomHandler
collection.unregister(MyCustomHandler)
collection.registered?(MyCustomHandler) #=> false

collection.register(SomeRandomClass) #=> ArgumentError
collection.unregister(SomeRandomClass) #=> ArgumentError
collection.choose(handler_name: :unknown) #=> Stenotype::UnknownHandlerError

Instance Method Summary collapse

Instance Method Details

#choose(handler_name:) ⇒ #as_json

Return a handler with given handler_name if found in collection, raises if a handler is not registered

Examples:

When a handler is present in the collection

collection = Stenotype::ContextHandlers::Collection.new
collection.register(MyCustomHandler) # with handler_name = :custom_handler
collection.choose(handler_name: :custom_handler) #=> MyCustomHandler

When a handler is not present in the collection

collection = Stenotype::ContextHandlers::Collection.new
collection.choose(handler_name: :custom_handler) #=> MyCustomHandler

Parameters:

  • handler_name (Symbol)

    a handler to be found in the collection

Returns:

  • (#as_json)

    A handler which respond to #as_json

Raises:

  • (Stenotype::Errors::UnknownHandler)

    in case a handler is not registered



48
49
50
51
52
53
54
55
56
57
# File 'lib/stenotype/context_handlers/collection.rb', line 48

def choose(handler_name:)
  handler = find_by(handler_name: handler_name)
  handler || raise(
    Stenotype::UnknownHandlerError,
    "Handler '#{handler_name}' is not found. "\
    "Please make sure the handler you've specified is "\
    "registered in the list of known handlers. "\
    "See #{Stenotype::ContextHandlers} for more information.",
  )
end

#unregister(handler) ⇒ Stenotype::ContextHandlers::Collection

TODO:

Add delete to the collectible delegation list and then use alias_method :unregister, :delete

Removes a registered handler.

Examples:

Register and unregister a handler

collection = Stenotype::ContextHandlers::Collection.new
collection.register(MyCustomHandler) # with handler_name = :custom_handler
collection.unregister(MyCustomHandler) # removes MyCustomHandler from the list of handlers

Parameters:

  • handler (#as_json)

    a handler to be removed from the collection of known handlers

Returns:



84
85
86
87
# File 'lib/stenotype/context_handlers/collection.rb', line 84

def unregister(handler)
  items.delete(handler)
  self
end