Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions lib/dry/auto_inject/builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think, it will be better to raise some fixed error, not RuntimeError. I think, it would be great for programmers. WDYT about it?


default[*dependency_names]
end

Expand All @@ -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)
Expand Down
34 changes: 34 additions & 0 deletions spec/integration/allow_inject_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# frozen_string_literal: true

RSpec.describe "allow condition" do
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

describe "allow" do
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

before do
module Test
AutoInject = Dry::AutoInject({one: 1, two: 2})
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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