Class: Dependencies

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

Class Method Summary collapse

Class Method Details

.[](*dependencies) ⇒ Object

Usage: “include Dependencies



16
17
18
19
20
21
22
23
# File 'lib/dependencies.rb', line 16

def [](*dependencies)
  class_dependencies = Low::DependencyFactory.parse([*dependencies])

  # "include" doesn't know the class that did the include, however "included" happens immediately after.
  Low::Dependencies.push(class_dependencies:)

  included_hook
end

.define_readers(dependencies, klass) ⇒ Object



52
53
54
55
56
57
58
59
60
# File 'lib/dependencies.rb', line 52

def define_readers(dependencies, klass)
  dependencies.each do |dependency|
    var_name = var_name_via_namespace(dependency.var_name)

    klass.define_method(var_name) do
      instance_variable_get("@#{var_name}")
    end
  end
end

.included_hookObject



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/dependencies.rb', line 25

def included_hook
  Module.new do
    def self.included(klass)
      klass.class_eval do
        # "include" doesn't know the class that did the include, however "included" happens immediately after.
        @low_dependencies = Low::Dependencies.pop

        class << self
          attr_reader :low_dependencies
        end

        def initialize
          self.class.low_dependencies.each do |dependency|
            provider = Low::Providers.find(dependency.provider_key)
            raise StandardError, "Provider #{dependency.provider_key} not found" if provider.nil?

            var_name = Providers.var_name_via_namespace(dependency.var_name)
            instance_variable_set("@#{var_name}", provider.result)
          end
        end

        Providers.define_readers(@low_dependencies, self)
      end
    end
  end
end

.provide(key, &block) ⇒ Object



11
12
13
# File 'lib/dependencies.rb', line 11

def provide(key, &block)
  Low::Dependencies.provide(key:, &block)
end

.var_name_via_namespace(namespace) ⇒ Object



62
63
64
65
66
# File 'lib/dependencies.rb', line 62

def var_name_via_namespace(namespace)
  return namespace.split('.').last if namespace.is_a?(String)

  namespace
end