Class: Carb::Inject::Injector

Inherits:
Object
  • Object
show all
Defined in:
lib/carb/inject/injector.rb

Overview

Creates an injector with the specified container

Instance Method Summary collapse

Constructor Details

#initialize(container = nil, auto_inject = false) ⇒ Injector

Initialize an injector that can be attached to a constant with the given container

Parameters:

  • container (#[], #has_key?) (defaults to: nil)

    must return dependencies based on dependency name

  • auto_inject (Boolean) (defaults to: false)

    if true, provides an initializer that auto injects dependencies by including AutoInjectable, false by default



24
25
26
27
# File 'lib/carb/inject/injector.rb', line 24

def initialize(container = nil, auto_inject = false)
  @container   = container || ::Carb::Container::ErrorContainer.new
  @auto_inject = auto_inject
end

Instance Method Details

#[](*dependencies, **aliased) ⇒ DependencyList

Returns module which can be included and will take care of automatically injecting not-supplied dependency.

Parameters:

  • dependencies (Array<#to_s>)

    Array of dependency names, which will be converted using Object#to_s, make sure the string version is a valid method name or it will raise, it will be used to create attr_readers on the object

  • aliased (Hash{Symbol => Object, Proc})

    if value is an Object, alias => dependency name hash, the alias must be a valid method name or it will raise. The aliases will be used to create attr_readers which will return the dependency from the container. If value is Proc, an attr_reader with the key as bane is created and value the output of invoking the Proc

Returns:

  • (DependencyList)

    module which can be included and will take care of automatically injecting not-supplied dependency

Raises:

  • (ArgumentError)

    if passed dependencies or aliased_dependencies contain objects not convertible to valid method names



43
44
45
46
47
48
49
# File 'lib/carb/inject/injector.rb', line 43

def [](*dependencies, **aliased)
  deps, lambdas = merge_dependencies(dependencies, aliased)
  wrapper = container
  wrapper = build_delegate(container, lambdas) unless lambdas.empty?

  Carb::Inject::DependencyList.new(wrapper, auto_inject, **deps)
end