Sha256: 967c1dfd60a21f2c2b20911bfef1a182796885e05bae153f3566b8869823b7a5

Contents?: true

Size: 1.58 KB

Versions: 3

Compression:

Stored size: 1.58 KB

Contents

module Flows
  module Plugin
    module DependencyInjector
      # Resolves dependencies on initialization and can inject it into class instance.
      #
      # @api private
      class DependencyList
        attr_reader :definitions
        attr_reader :provided_values
        attr_reader :dependencies

        def initialize(klass:, definitions:, provided_values:)
          @klass = klass
          @definitions = definitions
          @provided_values = provided_values.dup.tap { |pv| pv.default = NO_VALUE }

          check_missing_dependencies
          check_unexpected_dependencies
          resolve_dependencies
        end

        def inject_to(instance)
          dependencies.each { |dep| dep.inject_to(instance) }
        end

        private

        def required_dependencies
          definitions.select { |_, definition| definition.required }.keys
        end

        def check_missing_dependencies
          missing = required_dependencies - provided_values.keys

          raise MissingDependencyError.new(@klass, missing) if missing.any?
        end

        def check_unexpected_dependencies
          unexpected = provided_values.keys - definitions.keys

          raise UnexpectedDependencyError.new(@klass, unexpected) if unexpected.any?
        end

        def resolve_dependencies
          @dependencies = definitions.map do |name, definition|
            Dependency.new(
              klass: @klass,
              name: name,
              definition: definition,
              provided_value: provided_values[name]
            )
          end
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
flows-0.5.1 lib/flows/plugin/dependency_injector/dependency_list.rb
flows-0.5.0 lib/flows/plugin/dependency_injector/dependency_list.rb
flows-0.4.0 lib/flows/plugin/dependency_injector/dependency_list.rb