From b20de1905ccf247c045bcc8a912747857609da11 Mon Sep 17 00:00:00 2001 From: Anton Davydov Date: Tue, 30 Apr 2019 02:40:01 +0300 Subject: [PATCH] Proof of concept idea injection dependencies by specific pattern --- lib/dry/auto_inject/builder.rb | 11 +++++++++ spec/integration/allow_inject_spec.rb | 34 +++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 spec/integration/allow_inject_spec.rb diff --git a/lib/dry/auto_inject/builder.rb b/lib/dry/auto_inject/builder.rb index 97e8cec..e256524 100644 --- a/lib/dry/auto_inject/builder.rb +++ b/lib/dry/auto_inject/builder.rb @@ -15,10 +15,17 @@ class Builder < BasicObject def initialize(container, options = {}) @container = container @strategies = options.fetch(:strategies) { Strategies } + @pattern = options.fetch(:pattern) { nil } + end + + def allow(pattern) + AutoInject::Builder.new(@container, pattern: pattern, strategies: @strategies) end # @api public def [](*dependency_names) + raise unless match_by_pattern?(dependency_names) + default[*dependency_names] end @@ -28,6 +35,10 @@ def respond_to?(name, include_private = false) private + def match_by_pattern?(dependency_names) + @pattern.nil? || dependency_names.all? { |dependency| dependency.match(@pattern) } + end + def method_missing(name, *args, &block) if strategies.key?(name) Injector.new(container, strategies[name], builder: self) diff --git a/spec/integration/allow_inject_spec.rb b/spec/integration/allow_inject_spec.rb new file mode 100644 index 0000000..fa5e60a --- /dev/null +++ b/spec/integration/allow_inject_spec.rb @@ -0,0 +1,34 @@ +# frozen_string_literal: true + +RSpec.describe "allow condition" do + describe "allow" do + before do + module Test + AutoInject = Dry::AutoInject({one: 1, two: 2}) + OnlyOneInject = AutoInject.allow(/one/) + end + end + + subject(:instance) { including_class.new } + + context 'when user injects allowed keys' do + let(:including_class) do + Class.new do + include Test::OnlyOneInject[:one] + end + end + + it { expect(instance.one).to eq 1 } + end + + context 'when user injects all keys' do + let(:including_class) do + Class.new do + include Test::OnlyOneInject[:one, :two] + end + end + + it { expect { instance }.to raise_error } + end + end +end