Class: Injectable::Container

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

Overview

A simple container that can resolve dependencies.

Since:

  • 0.0.0

Instance Method Summary collapse

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



40
41
42
43
44
# File 'lib/injectable/container.rb', line 40

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(UserService)

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



22
23
24
25
26
27
28
29
# File 'lib/injectable/container.rb', line 22

def get(name)
  klass = implementing_class(name)
  if instantiated_objects.has_key?(klass)
    instantiated_objects[klass]
  else
    instantiated_objects[klass] = instantiate(klass)
  end
end

#register_implementation(name, klass) ⇒ Object

Register that instances of klass will perform the given role in this container context.

Examples:

Register that the user_finder role will be performed by

instances of DatabaseUserFinder
container.register_implementation(:user_finder, DatabaseUserFinder)

Parameters:

  • name (Symbol)

    The name of the role.

  • klass (Class)

    The name of the class performing this role.

Since:

  • 0.0.1



57
58
59
# File 'lib/injectable/container.rb', line 57

def register_implementation(name, klass)
  implementing_classes[name] = klass
end