Method: Needle::Container#namespace

Defined in:
lib/needle/container.rb

#namespace(name, opts = {}, &block) ⇒ Object

Create a new namespace within the container, with the given name. If a block is provided, it will be invoked when the namespace is created, with the new namespace passed to it.

For the curious, namespaces are simply services that are implemented by Container. The two statements are conceptually identical:

container.namespace( :calc )
container.register( :calc ) { |c,p| Needle::Container.new( c, p.name ) }

Note that this means that namespaces may be singletons or prototypes, or have immediate or deferred instantiation, and so forth. (The default of immediate, singleton instantiation is sufficient for 99% of the things you’ll use namespaces for.)

Usage:

container.namespace( :operations ) do |op|
  op.register( :add ) { Adder.new }
  ...
end

adder = container.calc.operations.add

Note: the block is not invoked until the namespace is created, which is not until it is first referenced. If you need the namespace to be created immediately, either use #namespace_define or reference the namespace as soon as you’ve created it.



174
175
176
177
178
179
180
# File 'lib/needle/container.rb', line 174

def namespace( name, opts={}, &block )
  register( name, opts ) do |c,p|
    ns = self[ :namespace_impl_factory ].new( c, name )
    block.call ns if block
    ns
  end
end