Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make Container hooks more useful for dynamic registration #274

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
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: 10 additions & 1 deletion lib/dry/system/container.rb
Original file line number Diff line number Diff line change
Expand Up @@ -329,8 +329,8 @@ def finalize!(freeze: true, &block)

@__finalized__ = true

self.freeze if freeze
hooks[:after_finalize].each { |hook| instance_eval(&hook) }
self.freeze if freeze
self
end

Expand Down Expand Up @@ -486,6 +486,15 @@ def root
config.root
end

# @api public
def register(key, *)
super

hooks[:after_register].each { |hook| instance_exec(key, &hook) }

self
end

# @api public
def resolve(key)
load_component(key) unless finalized?
Expand Down
44 changes: 44 additions & 0 deletions spec/unit/container/hooks/after_hooks_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# frozen_string_literal: true

RSpec.describe Dry::System::Container do
subject(:system) do
Class.new(described_class)
end

describe "after_register hook" do
it "executes after a new key is registered" do
expect { |hook|
system.after(:register, &hook)
system.register(:foo) { "bar" }
}.to yield_with_args(:foo)
end

it "provides the fully-qualified key" do
expect { |hook|
system.after(:register, &hook)
system.namespace :foo do
register(:bar) { "baz" }
end
}.to yield_with_args("foo.bar")
end
end

describe "after_finalize hook" do
it "executes after finalization" do
expect { |hook|
system.after(:finalize, &hook)
system.finalize!
}.to yield_control
end

it "executes before the container is frozen" do
is_frozen = nil

system.after(:finalize) { is_frozen = frozen? }
system.finalize!

expect(is_frozen).to eq false
expect(system).to be_frozen
end
end
end
Loading