Module: Tardigrade::Injector::ClassMethods

Defined in:
lib/tardigrade/injector.rb

Instance Method Summary collapse

Instance Method Details

#build_dependency(parent_instance, dep_klass) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/tardigrade/injector.rb', line 8

def build_dependency(parent_instance, dep_klass)
  if dep_klass.respond_to?(:argument_names) && dep_klass.argument_names.size > 0
    arguments = {}
    dep_klass.argument_names.each do |name|
      arguments[name] = parent_instance.send(name)
    end
    dep_klass.new(arguments)
  else
    dep_klass.respond_to?(:call) ? dep_klass : dep_klass.new
  end
end

#cache(name, value, memoize) ⇒ Object



28
29
30
31
32
33
34
# File 'lib/tardigrade/injector.rb', line 28

def cache(name, value, memoize)
  if memoize
    RequestStore.store[:"tardigrade_#{name}"] ||= value
  else
    value
  end
end

#call_method(klass) ⇒ Object



20
21
22
23
24
25
26
# File 'lib/tardigrade/injector.rb', line 20

def call_method(klass)
  if klass.respond_to?(:call)
    klass.method(:call)
  else
    klass.instance_method(:call)
  end
end

#import(*dependency_names) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/tardigrade/injector.rb', line 36

def import(*dependency_names)
  dependency_names.each do |dep_name|
    dep = Tardigrade.dependencies[dep_name]
    klass = dep[:class]
    memoize = dep[:memoize]

    if call_method(klass).arity == 0
      define_method(dep_name) do
        result = self.class.build_dependency(self, klass).call
        self.class.cache(dep_name, result, memoize)
      end
    else
      define_method(dep_name) do |*args|
        result = self.class.build_dependency(self, klass).call(*args)
        self.class.cache(dep_name, result, memoize)
      end
    end
  end
end