Sha256: 73d376d0ed9c52abe2f7b03572276f07ba1ee2cb152349a290924bd57beef414

Contents?: true

Size: 1.26 KB

Versions: 1

Compression:

Stored size: 1.26 KB

Contents

require "dry/auto_inject"

class Trailblazer::V2_1::Operation
  # Thanks, @timriley! <3
  # https://gist.github.com/timriley/d314a58da9784912159006e208ba8ea9
  module AutoInject
    class InjectStrategy < Module
      ClassMethods = Class.new(Module)

      attr_reader :container
      attr_reader :dependency_map
      attr_reader :class_mod

      def initialize(container, *dependency_names)
        @container = container
        @dependency_map = Dry::AutoInject::DependencyMap.new(*dependency_names)
        @class_mod = ClassMethods.new
      end

      def included(klass)
        define_call

        klass.singleton_class.prepend @class_mod

        super
      end

      private

      def define_call
        class_mod.class_exec(container, dependency_map) do |container, dependency_map|
          define_method :call_with_public_interface do |ctx={}, *dependencies|
            ctx_with_deps = dependency_map.to_h.each_with_object({}) { |(name, identifier), obj|
              obj[name] = ctx[name] || container[identifier]
            }.merge(ctx)

            super(ctx_with_deps, *dependencies)
          end
        end
      end
    end
  end

  def self.AutoInject(container)
    Dry::AutoInject(container, strategies: {default: AutoInject::InjectStrategy})
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
trailblazer-future-2.1.0.rc1 lib/trailblazer/v2_1/operation/auto_inject.rb