Class: Injectable::Container

Inherits:
Object
  • Object
show all
Includes:
Registerable
Defined in:
lib/injectable/container.rb

Overview

A simple container that can resolve dependencies.

Since:

  • 0.0.0

Defined Under Namespace

Classes: Unresolvable

Instance Method Summary collapse

Methods included from Registerable

#register_implementation

Constructor Details

#initialize(*objects) ⇒ Container

Create a new container with the objects needed to resolve dependencies and create new objects.

Examples:

Create the new container.

Injectable::Container.new(user, user_finder)

Parameters:

  • objects (Array<Object>)

    The dependencies.

Since:

  • 0.0.0



44
45
46
47
48
# File 'lib/injectable/container.rb', line 44

def initialize(*objects)
  objects.each do |object|
    instantiated_objects[object.class] = object
  end
end

Instance Method Details

#get(name) ⇒ Object

Get an instance of an object from the container with the provided class.

Examples:

Get an instance of an object for class UserService.

container.get(:user_service)

Parameters:

  • name (Symbol)

    the role which the returned object should perform.

Returns:

  • (Object)

    The instantiated object.

Raises:

  • (Injectable::RoleNotRegistered)

    if queried for a role which is not registered

Since:

  • 0.0.0



25
26
27
28
29
30
31
32
33
# File 'lib/injectable/container.rb', line 25

def get(name)
  classes = registered_implementations(name)
  if klass = instantiated_class(classes)
    instantiated_objects[klass]
  else
    object = instantiate(classes)
    instantiated_objects[object.class] = object
  end
end