Class: SleepingKingStudios::Tools::Messages::Registry

Inherits:
Object
  • Object
show all
Defined in:
lib/sleeping_king_studios/tools/messages/registry.rb

Overview

Matches defined message strategies by message scope.

Defined Under Namespace

Classes: StrategyAlreadyExistsError

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeRegistry

Returns a new instance of Registry.



45
46
47
48
# File 'lib/sleeping_king_studios/tools/messages/registry.rb', line 45

def initialize
  @strategies = {}
  @root       = Node.new(scope: :root)
end

Class Method Details

.globalRegistry

Returns a singleton instance of the messages registry, instantiating the instance if needed.

Returns:

  • (Registry)

    the messages registry singleton.



19
20
21
# File 'lib/sleeping_king_studios/tools/messages/registry.rb', line 19

define_method :global do
  semaphore.synchronize { @global ||= new }
end

Instance Method Details

#get(scope) ⇒ SleepingKingStudios::Tools::Messages::Strategy? Also known as: []

Returns the strategy matching the given scope or key.

The returned strategy will match the longest defined scope that matches the given key.

Parameters:

  • scope (String)

    the requested scope or key.

Returns:



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/sleeping_king_studios/tools/messages/registry.rb', line 59

def get(scope)
  validate_scope(scope)

  node     = root
  strategy = nil

  scope.to_s.split('.').each do |segment|
    node = node[segment]

    break if node.nil?

    strategy = node.strategy if node.strategy
  end

  strategy
end

#register(scope:, strategy:, force: false) ⇒ self #register(scope:, hash:, force: false) ⇒ Object #register(scope:, file:, force: false) ⇒ Object Also known as: add

Overloads:

  • #register(scope:, strategy:, force: false) ⇒ self

    Adds a strategy to the registry with the given scope.

    Parameters:

    • scope (String)

      the scope for the strategy.

    • strategy (SleepingKingStudios::Tools::Messages::Strategy)

      the strategy to register.

    • force (true, false) (defaults to: false)

      if true, overrides an existing strategy with the given scope. Defaults to false.

    Returns:

    • (self)

      the registry.



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/sleeping_king_studios/tools/messages/registry.rb', line 91

def register(scope:, force: false, **)
  validate_scope(scope)

  strategy = resolve_strategy(**)

  if strategies.key?(scope.to_s) && !force
    raise StrategyAlreadyExistsError,
      "strategy already exists with scope #{scope}"
  end

  @strategies[scope.to_s] = strategy

  add_node(scope:, strategy:)

  self
end

#strategiesHash

Returns the registered strategies for the registry.

Returns:

  • (Hash)

    the registered strategies for the registry.



110
111
112
# File 'lib/sleeping_king_studios/tools/messages/registry.rb', line 110

def strategies
  @strategies.dup.freeze
end