Class: Serf::Loader::Registry
- Inherits:
-
Object
- Object
- Serf::Loader::Registry
- Defined in:
- lib/serf/loader/registry.rb
Overview
A Registry of components that can then be wired up dependency injection style using the Service Locator Pattern. Components are lazily evaluated and memoized. Thus all components are singletons.
# Create a new registry
registry = Registry.new
# Registers a component
registry.add 'a_comp' do |r|
12345
end
# Registers b component that uses a component
registry.add 'b_comp' do |r|
{
a_value: r['a_comp']
}
end
# Registers a Serf app (serf is helper to make and execute
# a Serf::Builder), using the long form builder DSL.
registry.add 'subsystem/request/my_request' do |r|
# Register a serf to handle this request
serf do
use_defaults
run MyInteractor.new(b_comp: r['b_comp'])
end
end
# Now obtain the build serf, all wired up, by the parcel kind
# and execute the found serf.
parcel = {
kind: 'subsystem/request/my_request',
message: {}
}
serf = registry[parcel[:kind]]
puts serf.call(parcel)
Instance Attribute Summary collapse
-
#blocks ⇒ Object
readonly
Returns the value of attribute blocks.
-
#env ⇒ Object
readonly
Returns the value of attribute env.
-
#values ⇒ Object
readonly
Returns the value of attribute values.
Instance Method Summary collapse
-
#[](name) ⇒ Object
Looks up a component instance by name.
-
#add(name, &block) ⇒ Object
Adds a component to the registry.
-
#initialize(*args) ⇒ Registry
constructor
A new instance of Registry.
Constructor Details
#initialize(*args) ⇒ Registry
Returns a new instance of Registry.
54 55 56 57 58 59 |
# File 'lib/serf/loader/registry.rb', line 54 def initialize(*args) opts = Optser. args @blocks = {} @values = {} @env = opts.get(:env) { Hashie::Mash.new } end |
Instance Attribute Details
#blocks ⇒ Object (readonly)
Returns the value of attribute blocks.
50 51 52 |
# File 'lib/serf/loader/registry.rb', line 50 def blocks @blocks end |
#env ⇒ Object (readonly)
Returns the value of attribute env.
52 53 54 |
# File 'lib/serf/loader/registry.rb', line 52 def env @env end |
#values ⇒ Object (readonly)
Returns the value of attribute values.
51 52 53 |
# File 'lib/serf/loader/registry.rb', line 51 def values @values end |
Instance Method Details
#[](name) ⇒ Object
Looks up a component instance by name.
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
# File 'lib/serf/loader/registry.rb', line 77 def [](name) name = name.to_sym return values[name] if values.has_key? name # No memoized value, so grab the block, call it and memoize it # return the block's return value, or nil. if block = blocks[name] begin value = block.call self, env values[name] = value blocks.delete name return value rescue => e raise Serf::Errors::LoadFailure.new("Name: #{name}", e) end end end |
#add(name, &block) ⇒ Object
Adds a component to the registry.
67 68 69 |
# File 'lib/serf/loader/registry.rb', line 67 def add(name, &block) blocks[name.to_sym] = block end |