Module: Medicine::DI

Defined in:
lib/medicine.rb

Instance Method Summary collapse

Instance Method Details

#initialize(injections = {}) ⇒ undefined

Injects dependencies

Examples:

register_user = RegisterUser.new(user_repo: double('UserRepo'))

Parameters:

  • args (Array<Object>)
    • the last argument must be a Hash

Returns:

  • (undefined)


33
34
35
36
37
# File 'lib/medicine.rb', line 33

def initialize(injections = {})
  @injections = Injections.new
  injects(injections)
  super()
end

#inject_dependency(name, dependency) ⇒ self

Injects a dependency

Examples:

register_user.inject_dependency(:user_repo, double('UserRepo'))

Parameters:

  • key (Symbol)
  • dependency (Object)

Returns:

  • (self)

Raises:



50
51
52
53
54
# File 'lib/medicine.rb', line 50

def inject_dependency(name, dependency)
  raise DependencyUnknownError, "#{name} has not been declared as a dependency" unless self.class.dependencies.include?(name)
  @injections.set(name, dependency)
  self
end

#injectionsInjections

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 injections

Examples:

register_user.injections

Returns:



78
79
80
# File 'lib/medicine.rb', line 78

def injections
  @injections.dup.freeze
end

#injects(injections) ⇒ self

Injects dependencies

Examples:

register_user.injects(user_repo: double, user_mailer: double)

Returns:

  • (self)


66
67
68
# File 'lib/medicine.rb', line 66

def injects(injections)
  injections.each { |name, dependency| inject_dependency(name, dependency) }
end