Class: Corindon::DependencyInjection::Container

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeContainer

Returns a new instance of Container.



12
13
14
15
16
17
# File 'lib/corindon/dependency_injection/container.rb', line 12

def initialize
  @services = {}
  @definitions = {}

  @injector = Injector.new(container: self)
end

Instance Attribute Details

#definitionsObject (readonly)

Returns the value of attribute definitions.



8
9
10
# File 'lib/corindon/dependency_injection/container.rb', line 8

def definitions
  @definitions
end

#injectorObject (readonly)

Returns the value of attribute injector.



9
10
11
# File 'lib/corindon/dependency_injection/container.rb', line 9

def injector
  @injector
end

#servicesObject (readonly)

Returns the value of attribute services.



10
11
12
# File 'lib/corindon/dependency_injection/container.rb', line 10

def services
  @services
end

Instance Method Details

#add_definition(klass, &block) ⇒ Object

Parameters:

  • klass (Class)


20
21
22
23
24
25
26
27
28
# File 'lib/corindon/dependency_injection/container.rb', line 20

def add_definition(klass, &block)
  @definitions[to_id(klass)] = if injectable?(klass)
                                 klass.definition
                               elsif block.sth?
                                 Dsl.new(klass).exec(&block)
                               else
                                 Definition.new(klass)
                               end
end

#get(key) ⇒ Object

Parameters:

  • key (Class, #to_s)

Returns:

  • (Object)


38
39
40
41
42
43
44
45
46
47
48
# File 'lib/corindon/dependency_injection/container.rb', line 38

def get(key)
  id = to_id(key)

  if has?(key)
    services.fetch(id) { build_service(id) }
  elsif injectable?(key)
    key.definition.build(injector)
  else
    raise StandardError.new("No service #{id}")
  end
end

#has?(key) ⇒ Boolean

Parameters:

  • key (Class, #to_s)

Returns:

  • (Boolean)


32
33
34
# File 'lib/corindon/dependency_injection/container.rb', line 32

def has?(key)
  @definitions.key?(to_id(key))
end