Sha256: eff4f9a8644b04c3ffb3879cb935e8a245f6ed0177bf883c6226e336622fa5ca

Contents?: true

Size: 1.32 KB

Versions: 1

Compression:

Stored size: 1.32 KB

Contents

require "dry-auto_inject"

module Dry
  module Component
    class Injector
      # @api private
      attr_reader :container

      # @api private
      attr_reader :injector

      # @api private
      def initialize(container, strategy: :args, strategies_cache: nil)
        @container = container
        @strategies = strategies_cache

        @injector = if strategy == :args
          Dry::AutoInject(container)
        else
          Dry::AutoInject(container).send(strategy)
        end
      end

      # @api public
      def [](*deps)
        load_components(*deps)
        injector[*deps]
      end

      # @api public
      def args
        strategies[:args]
      end

      # @api public
      def hash
        strategies[:hash]
      end

      # @api public
      def kwargs
        strategies[:kwargs]
      end

      private

      def load_components(*components)
        components = components.dup
        aliases = components.last.is_a?(Hash) ? components.pop : {}

        (components + aliases.values).each do |key|
          container.load_component(key) unless container.key?(key)
        end
      end

      def strategies
        @strategies ||= Hash.new do |cache, strategy|
          cache[strategy] = self.class.new(container, strategy: strategy, strategies_cache: cache)
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
dry-component-0.1.0 lib/dry/component/injector.rb