Class: Serf::Loader::Registry

Inherits:
Object
  • Object
show all
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

Instance Method Summary collapse

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.extract_options! args
  @blocks = {}
  @values = {}
  @env = opts.get(:env) { Hashie::Mash.new }
end

Instance Attribute Details

#blocksObject (readonly)

Returns the value of attribute blocks.



50
51
52
# File 'lib/serf/loader/registry.rb', line 50

def blocks
  @blocks
end

#envObject (readonly)

Returns the value of attribute env.



52
53
54
# File 'lib/serf/loader/registry.rb', line 52

def env
  @env
end

#valuesObject (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