Skip to content

Commit

Permalink
lazy deps
Browse files Browse the repository at this point in the history
  • Loading branch information
xronos-i-am committed Dec 12, 2024
1 parent f22da02 commit dffb3c7
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 22 deletions.
22 changes: 18 additions & 4 deletions lib/active_dry_deps/container.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,29 @@ class Container < Hash

def resolve(container_key)
unless key?(container_key)
self[container_key] = Object.const_get(container_key)
self[container_key] = Entry.new(value: Object.const_get(container_key))
end

self[container_key]
self[container_key]&.value
end

def register(container_key)
self[container_key.to_s] = yield
def register(container_key, &block)
self[container_key.to_s] = Entry.new(proc: block)
end

Entry =
Struct.new(:input) do
def initialize(input = {})
super
@value = input[:value] if input.key?(:value)
end

def value
return @value if defined? @value

@value = input.fetch(:proc).call
end
end

end
end
16 changes: 4 additions & 12 deletions lib/active_dry_deps/stub.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ module ActiveDryDeps

module StubDeps

def stub(key, proxy_object, &block)
self::CONTAINER.stub(key, proxy_object, &block)
def stub(key, &block)
self::CONTAINER.stub(key, &block)
end

def unstub(*keys)
Expand All @@ -20,16 +20,8 @@ def self.extended(container)
const_set(:CONTAINER_ORIG, container.dup)
end

def stub(key, proxy_object)
if block_given?
begin
self[key] = proxy_object
ensure
unstub(key)
end
else
self[key] = proxy_object
end
def stub(key, &block)
self[key] = ActiveDryDeps::Container::Entry.new(proc: block)
end

def unstub(*unstub_keys)
Expand Down
17 changes: 11 additions & 6 deletions spec/active_dry_deps_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ def expect_call_orig
expect(CreateOrder.call).to eq %w[CreateDeparture CreateDeparture job-performed message-ok email-sent-hello]
end

it 'direct stub with `Deps.stub`' do
Deps.stub('CreateDeparture', double(call: '1'))
it 'stubs dependency at the container level' do
Deps.stub('CreateDeparture') { double(call: '1') }

expect(CreateOrder.call).to eq %w[1 1 job-performed message-ok email-sent-hello]

Expand All @@ -46,10 +46,15 @@ def expect_call_orig
expect_call_orig
end

it 'direct stub with `Deps.sub` with block' do
Deps.stub('CreateDeparture', double(call: '1')) do
expect(CreateOrder.call).to eq %w[1 1 job-performed message-ok email-sent-hello]
end
it 'raises exception when calls a stub block' do
expect {
Deps.stub('CreateDeparture') { raise StandardError, 'Something went wrong' }
}.not_to raise_error

expect { CreateOrder.call }
.to raise_error(StandardError, 'Something went wrong')

Deps.unstub

expect_call_orig
end
Expand Down

0 comments on commit dffb3c7

Please sign in to comment.