Class: Poniard::Injector

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

Overview

A parameter pased dependency injector. Figures out which arguments to call a method with based on the names of method’s parameters. Multiple sources can be provided to lookup parameter values. They are checked in reverse order.

The injector itself is always available to methods via the injector parameter.

Examples:

def my_method(printer)
  printer.("hello!")
end

Injector.new([{
  printer: ->(msg) { puts msg }
}]).dispatch(method(:my_method))

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sources = []) ⇒ Injector

Returns a new instance of Injector.



21
22
23
24
25
26
27
28
29
# File 'lib/poniard/injector.rb', line 21

def initialize(sources = [])
  @sources = sources.map {|source|
    if source.is_a? Hash
      HashSource.new(source)
    else
      ObjectSource.new(self, source)
    end
  } + [HashSource.new(injector: self)]
end

Instance Attribute Details

#sourcesObject (readonly)

Returns the value of attribute sources.



19
20
21
# File 'lib/poniard/injector.rb', line 19

def sources
  @sources
end

Instance Method Details

#dispatch(method, overrides = {}) ⇒ Object

Call the given method with arguments. If a parameter is not provided by any source, an UnknownInjectable instance is passed instead.



33
34
35
# File 'lib/poniard/injector.rb', line 33

def dispatch(method, overrides = {})
  dispatch_method(method, UnknownInjectable.method(:new), overrides)
end

#eager_dispatch(method, overrides = {}) ⇒ Object

Same as #dispatch, except it raises an exception immediately if any parameter is not provided by sources.



39
40
41
42
43
# File 'lib/poniard/injector.rb', line 39

def eager_dispatch(method, overrides = {})
  dispatch_method(method, ->(name) {
    ::Kernel.raise UnknownParam, name
  }, overrides)
end