Class: Dry::AutoInject

Inherits:
Object
  • Object
show all
Defined in:
lib/dry/auto_inject.rb,
lib/dry/auto_inject/version.rb

Overview

Main DSL class

Constant Summary collapse

VERSION =
'0.0.1'.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ AutoInject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of AutoInject.



51
52
53
54
# File 'lib/dry/auto_inject.rb', line 51

def initialize(&block)
  instance_exec(&block)
  @injection = -> *names { Injection.new(names, @container) }
end

Instance Attribute Details

#injectionObject (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



12
13
14
# File 'lib/dry/auto_inject.rb', line 12

def injection
  @injection
end

Class Method Details

.new(&block) ⇒ Dry::AutoInject::Injection

Configure an auto-injection module

Examples:

# set up your container
my_container = Dry::Container.new

my_container.register(:data_store, -> { DataStore.new })
my_container.register(:user_repository, -> { container[:data_store][:users] })
my_container.register(:persist_user, -> { PersistUser.new })

# set up your auto-injection module

AutoInject = Dry::AutoInject.new { container(my_container) }

# then simply include it in your class providing which dependencies should be
# injected automatically from the configure container
class PersistUser
  include AutoInject[:user_repository]

  def call(user)
    user_repository << user
  end
end

persist_user = my_container[:persist_user]

persist_user.call(name: 'Jane')

Returns:

  • (Dry::AutoInject::Injection)


45
46
47
48
# File 'lib/dry/auto_inject.rb', line 45

def self.new(&block)
  dsl = super(&block)
  dsl.injection
end

Instance Method Details

#container(container) ⇒ Object

Set up the container for the injection module



59
60
61
# File 'lib/dry/auto_inject.rb', line 59

def container(container)
  @container = container
end