Class: Dinja::Container
- Inherits:
-
Object
- Object
- Dinja::Container
- Defined in:
- lib/dinja/container.rb
Overview
Dependency injection container
Defined Under Namespace
Classes: DependencyAlreadyRegistered, DependencyNotRegistered
Instance Attribute Summary collapse
-
#dependencies ⇒ Object
readonly
Returns the value of attribute dependencies.
Instance Method Summary collapse
-
#initialize ⇒ Container
constructor
A new instance of Container.
-
#lookup(key) ⇒ Object
Look up a dependency without resolving it.
-
#lookup!(key) ⇒ Object
Look up a dependency without resolving it.
-
#register(key, &block) ⇒ Object
Register a dependency.
-
#register!(key, &block) ⇒ Object
Register or overwrite an existing dependency.
-
#resolve(key, *args, **kwargs, &block) ⇒ Object
Resolve a dependency.
-
#resolve!(key, *args, **kwargs, &block) ⇒ Object
Resolve a dependency.
Constructor Details
#initialize ⇒ Container
Returns a new instance of Container.
8 9 10 |
# File 'lib/dinja/container.rb', line 8 def initialize @dependencies = {} end |
Instance Attribute Details
#dependencies ⇒ Object (readonly)
Returns the value of attribute dependencies.
6 7 8 |
# File 'lib/dinja/container.rb', line 6 def dependencies @dependencies end |
Instance Method Details
#lookup(key) ⇒ Object
Look up a dependency without resolving it
40 41 42 43 44 |
# File 'lib/dinja/container.rb', line 40 def lookup(key) raise DependencyNotRegistered, "Dependency not registered: #{key}" unless dependencies.key?(key) dependencies[key] end |
#lookup!(key) ⇒ Object
Look up a dependency without resolving it
50 51 52 |
# File 'lib/dinja/container.rb', line 50 def lookup!(key) dependencies[key] end |
#register(key, &block) ⇒ Object
Register a dependency
19 20 21 22 23 |
# File 'lib/dinja/container.rb', line 19 def register(key, &block) raise DependencyAlreadyRegistered, "Dependency already registered: #{key}" if dependencies.key?(key) register!(key, &block) end |
#register!(key, &block) ⇒ Object
Register or overwrite an existing dependency
30 31 32 |
# File 'lib/dinja/container.rb', line 30 def register!(key, &block) dependencies[key] = block end |
#resolve(key, *args, **kwargs, &block) ⇒ Object
Resolve a dependency
62 63 64 |
# File 'lib/dinja/container.rb', line 62 def resolve(key, *args, **kwargs, &block) lookup(key).call(*args, **kwargs, &block) end |
#resolve!(key, *args, **kwargs, &block) ⇒ Object
Resolve a dependency
72 73 74 |
# File 'lib/dinja/container.rb', line 72 def resolve!(key, *args, **kwargs, &block) lookup!(key)&.call(*args, **kwargs, &block) end |