From 9629ae59e587b7b4d250b661cd01b6afa2682209 Mon Sep 17 00:00:00 2001 From: Sean Collins Date: Wed, 16 Feb 2022 18:01:50 -0400 Subject: [PATCH] Add isolate feature to Loader --- lib/dry/system/loader.rb | 13 +++++++++++-- spec/unit/loader_spec.rb | 7 +++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/lib/dry/system/loader.rb b/lib/dry/system/loader.rb index f93923356..c16b50693 100644 --- a/lib/dry/system/loader.rb +++ b/lib/dry/system/loader.rb @@ -41,16 +41,25 @@ def require!(component) # @return [Object] # # @api public - def call(component, *args) + def call(component, *args, isolate: false) require!(component) constant = self.constant(component) - if singleton?(constant) + instance = if singleton?(constant) constant.instance(*args) else constant.new(*args) end + + if isolate + constant_name_parts = constant.to_s.split("::") + namespace = constant_name_parts.slice(0..-2).join("::") + namespace_const = component.inflector.constantize(namespace) + namespace_const.send(:remove_const, constant_name_parts.last) + end + + instance end ruby2_keywords(:call) if respond_to?(:ruby2_keywords, true) diff --git a/spec/unit/loader_spec.rb b/spec/unit/loader_spec.rb index c978838e9..072952f29 100644 --- a/spec/unit/loader_spec.rb +++ b/spec/unit/loader_spec.rb @@ -71,6 +71,13 @@ module Test end it_behaves_like "object loader" + + it "isolates component by removing its constant" do + constant + instance = loader.call(component, isolate: true) + expect(Test.const_defined?("Bar")).to eq(false) + expect(instance).to be_a(constant) + end end context "with a constructor accepting args" do