Class: Needle::Container

Inherits:
Object
  • Object
show all
Defined in:
lib/needle/container.rb

Overview

The container is the heart of Needle’s model. Every Container instance is a miniature registry, and is really a namespace separate from every other Container instance. Service lookups inside of a container always look in self first, and if not found, they then look in their parent container, recursively.

You will rarely need to instantiate a Container directly. Instead, use the Container#namespace method to create new containers.

Direct Known Subclasses

Registry

Defined Under Namespace

Classes: DefinitionContext

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parent = nil, name = nil) ⇒ Container

Create a new empty container with the given parent and name.



118
119
120
121
122
123
124
125
# File 'lib/needle/container.rb', line 118

def initialize( parent=nil, name=nil )
  @root = nil
  @builder = nil

  @name = name
  @parent = parent
  @service_points = Hash.new
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args, &block) ⇒ Object

As a convenience for accessing services, this delegates any message sent to the container (which has no parameters and no block) to Container#[]. Note that this incurs slightly more overhead than simply calling Container#[] directly, so if performance is an issue, you should avoid this approach.

Usage:

container.register( :add ) { Adder.new }
p container.add == container[:add] # => true

This also allows you to register new services in the container by sending the container a message with an attached block.

Usage:

container.foo { Bar.new }
p container.foo


440
441
442
443
444
445
446
# File 'lib/needle/container.rb', line 440

def method_missing( sym, *args, &block )
  if block.nil? && args.empty? && knows_key?( sym )
    self[sym]
  else
    super
  end
end

Instance Attribute Details

#nameObject (readonly)

The name of this container. May be nil.



115
116
117
# File 'lib/needle/container.rb', line 115

def name
  @name
end

#parentObject (readonly)

The container that contains this container. This will be nil for the root of a hierarchy (see Registry).



112
113
114
# File 'lib/needle/container.rb', line 112

def parent
  @parent
end

Instance Method Details

#[](name) ⇒ Object

Retrieves the named service, if it exists. Ancestors are searched if the service is not defined by the current container (see #find_definition). If the named service does not exist, ServiceNotFound is raised.

Note that this returns the instantiated service, not the service point.

Raises:



360
361
362
363
364
365
# File 'lib/needle/container.rb', line 360

def []( name )
  point = find_definition( name )
  raise ServiceNotFound, "#{fullname}.#{name}" unless point

  point.instance
end

#builderObject

Returns the DefinitionContext instance that can be used to “build” this container.



147
148
149
# File 'lib/needle/container.rb', line 147

def builder
  @builder ||= DefinitionContext.new( self )
end

#define {|builder| ... } ⇒ Object

If a block is given, yields the container’s builder instance to the block. Otherwise, simply returns the builder instance.

Usage:

container.define do |b|
  b.foo { Bar.new }
  b.baz { Baz.new }
  ...
end

Or:

container.define.foo { Bar.new }
container.define.baz { Baz.new }

Yields:



166
167
168
169
# File 'lib/needle/container.rb', line 166

def define
  yield builder if block_given?
  builder
end

#define!(&block) ⇒ Object

Create a new DefinitionContext around the container, and then evaluate the block within the new context instance (via instance_eval).

Usage:

container.define! do
  calc( :model => :prototype ) { Calc.new( operations ) }
end

Raises:

  • (ArgumentError)


179
180
181
182
183
# File 'lib/needle/container.rb', line 179

def define!( &block )
  raise ArgumentError, "block expected" unless block
  builder.instance_eval( &block )
  self
end

#find_definition(name) ⇒ Object

Searches the current container and its ancestors for the named service. If found, the service point (the definition of that service) is returned, otherwise nil is returned.



349
350
351
352
353
# File 'lib/needle/container.rb', line 349

def find_definition( name )
  point = @service_points[ name ]
  point = @parent.find_definition( name ) if @parent unless point
  point
end

#fullnameObject

Return the fully qualified name of this container, which is the container’s name and all parent’s names up to the root container, catenated together with dot characters, i.e., “one.two.three”.



139
140
141
142
143
# File 'lib/needle/container.rb', line 139

def fullname
  parent_name = ( @parent ? @parent.fullname : nil )
  return @name.to_s unless parent_name
  "#{parent_name}.#{@name}"
end

#has_key?(name) ⇒ Boolean

Returns true if this container includes a service point with the given name. Returns false otherwise.

Returns:

  • (Boolean)


369
370
371
# File 'lib/needle/container.rb', line 369

def has_key?( name )
  @service_points.has_key?( name )
end

#intercept(name) ⇒ Object

Describe a new interceptor to use that will intercept method calls on the named service. This method returns a new Interceptor instance, which can be used directly to configure the behavior of the interceptor.

Usage:

container.intercept( :calc ).with { |c| c.logging_interceptor }

Raises:



321
322
323
324
325
326
327
328
329
# File 'lib/needle/container.rb', line 321

def intercept( name )
  point = find_definition( name )
  raise ServiceNotFound, "#{fullname}.#{name}" unless point

  interceptor = Interceptor.new
  point.interceptor interceptor

  interceptor
end

#keysObject

Return an array of the names of all service points in this container.



382
383
384
# File 'lib/needle/container.rb', line 382

def keys
  @service_points.keys
end

#knows_key?(name) ⇒ Boolean

Returns true if this container or any ancestor includes a service point with the given name. Returns false otherwise.

Returns:

  • (Boolean)


375
376
377
378
379
# File 'lib/needle/container.rb', line 375

def knows_key?( name )
  return true if has_key?( name )
  return @parent.knows_key?( name ) if @parent
  false
end

#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 really 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.



234
235
236
237
238
239
240
# File 'lib/needle/container.rb', line 234

def namespace( name, opts={}, &block )
  register( name, opts ) do |c,p|
    ns = Container.new( c, name )
    block.call ns if block
    ns
  end
end

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

Create a new namespace within the container, with the given name. The block (which is required) will be passed to Container#define on the new namespace.

For the curious, namespaces are simply services that are implemented by Container. The two statements are really 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_define( :operations ) do |b|
  b.add { Adder.new }
  ...
end

adder = container.calc.operations.add

Note: this method will immediately instantiate the new namespace, unlike #namespace. If you want instantiation of the namespace to be deferred, either use a deferring service model (like :singleton_deferred) or create the namespace via #namespace.

Raises:

  • (ArgumentError)


308
309
310
311
312
# File 'lib/needle/container.rb', line 308

def namespace_define( name, opts={}, &block )
  raise ArgumentError, "block expected" unless block
  namespace( name, opts ) { |ns| ns.define( &block ) }
  self[name]
end

#namespace_define!(name, opts = {}, &block) ⇒ Object Also known as: namespace!

Create a new namespace within the container, with the given name. The block (which is required) will be passed to Container#define! on the new namespace.

For the curious, namespaces are simply services that are implemented by Container. The two statements are really 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_define!( :operations ) do
  add { Adder.new }
  ...
end

adder = container.calc.operations.add

Note: this method will immediately instantiate the new namespace, unlike #namespace. If you want instantiation of the namespace to be deferred, either use a deferring service model (like :singleton_deferred) or create the namespace via #namespace.

Raises:

  • (ArgumentError)


271
272
273
274
275
# File 'lib/needle/container.rb', line 271

def namespace_define!( name, opts={}, &block )
  raise ArgumentError, "block expected" unless block
  namespace( name, opts ) { |ns| ns.define!( &block ) }
  self[name]
end

#pipeline(name) ⇒ Object

Returns the pipeline object for the named service, which allows clients to explicitly manipulate the service’s instantiation pipeline.

Usage:

container.pipeline( :calc ).
  add( :initialize ).
  add( :custom ) { |me,*args| me.succ.call( *args ) }

Raises:



339
340
341
342
343
344
# File 'lib/needle/container.rb', line 339

def pipeline( name )
  point = find_definition( name )
  raise ServiceNotFound, "#{fullname}.#{name}" unless point

  point.pipeline
end

#register(name, opts = {}, &callback) ⇒ Object

Register the named service with the container. When the service is requested (with Container#[]), the associated callback will be used to construct it.

This returns the registry that was used to register the service.

Usage:

container.register( :calc, :model=>:prototype ) do |c|
  Calc.new( c.operations )
end

Raises:

  • (ArgumentError)


196
197
198
199
200
201
202
203
204
# File 'lib/needle/container.rb', line 196

def register( name, opts={}, &callback )
  raise ArgumentError, "expect block" unless callback

  name = name.to_s.intern unless name.is_a?( Symbol )
  @service_points[ name ] =
    ServicePoint.new( self, name, opts, &callback )

  self
end

#require(file, target_name, registration_method = :register_services) ⇒ Object

Require the given file, and then invoke the given registration method on the target module. The container will be passed as the sole parameter to the registration method. This allows you to easily decentralize the definition of services.

Usage:

container.require( "app/services", "App::Services" )

# in app/services.rb:

module App
  module Services

    def register_services( container )
      ...
    end
    module_function :register_services

  end
end


407
408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'lib/needle/container.rb', line 407

def require( file, target_name, registration_method=:register_services )
  Kernel.require file

  if target_name.is_a?( Module )
    target = target_name
  else
    target = Object
    target_name.to_s.split( /::/ ).each do |element|
      target = target.const_get( element )
    end
  end

  target.__send__( registration_method, self )
end

#respond_to?(sym) ⇒ Boolean

Returns true if this container responds to the given message, or if it explicitly contains a service with the given name (see #has_key?). In this case, #has_key? is used instead of #knows_key? so that subcontainers may be used as proper hashes by their parents.

Returns:

  • (Boolean)


452
453
454
# File 'lib/needle/container.rb', line 452

def respond_to?( sym )
  @service_points.has_key?( sym ) || super
end

#rootObject

Returns the root of the current hierarchy. If the container is the root, returns self, otherwise calls Container#root on its parent. The value is cached for future reference.



130
131
132
133
134
# File 'lib/needle/container.rb', line 130

def root
  return @root if @root
  return self if parent.nil?
  @root = parent.root
end