class Dio::Injector

Injector executes dependency injection. You can register and inject dependencies using this class.

Public Class Methods

new(container = Dio::Container.new, loader_factory = Dio::LoaderFactory.new) click to toggle source
# File lib/dio/injector.rb, line 29
def initialize(container = Dio::Container.new, loader_factory = Dio::LoaderFactory.new)
  @container = container
  @loader_factory = loader_factory
  @original_container = nil
end

Public Instance Methods

create(clazz, *args) click to toggle source

Creates a new instance of the given class. Dio injects dependencies to the created instance.

@param clazz [Class] @param args [Array] @return Instance of clazz

# File lib/dio/injector.rb, line 71
def create(clazz, *args)
  raise ArgumentError, "#{clazz} is not a class" unless clazz.is_a?(Class)
  inject(clazz.new(*args))
end
inject(target) click to toggle source

Inject dependencies to the given object.

@param target [Object] @return target

# File lib/dio/injector.rb, line 56
def inject(target)
  unless injectable?(target)
    raise ArgumentError, 'The given object does not include Dio module'
  end
  loader = @loader_factory.create(@container, target)
  target.__dio_inject__(loader)
  target
end
register(key, object = nil) { |*args| ... } click to toggle source

Registers a new dependency with the given key. You can specify either an object or a factory block that creates an object.

@param key [Object] Typically a class or a symbol. @param object [Object] @yield passed arguments when loading @return [Dio::Injector] self

# File lib/dio/injector.rb, line 43
def register(key, object = nil)
  assert_register_args_valid(object, block_given?)
  @container.register(key) do |*args|
    object = yield(*args) if block_given?
    injectable?(object) ? inject(object) : object
  end
  self
end

Private Instance Methods

assert_register_args_valid(object, block_given) click to toggle source
# File lib/dio/injector.rb, line 78
def assert_register_args_valid(object, block_given)
  return if (object || block_given) && !(object && block_given)
  raise ArgumentError, 'You must specify either an object OR a block'
end
injectable?(object) click to toggle source
# File lib/dio/injector.rb, line 83
def injectable?(object)
  object.respond_to?(:__dio_inject__)
end