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