diff --git a/lib/dependor/core_ext.rb b/lib/dependor/core_ext.rb index 26bfb95..cd4f397 100644 --- a/lib/dependor/core_ext.rb +++ b/lib/dependor/core_ext.rb @@ -1,2 +1,3 @@ Object.extend Dependor::TakesExt +Object.extend Dependor::ClassTakesExt Transient = Dependor::Transient diff --git a/lib/dependor/instantiator.rb b/lib/dependor/instantiator.rb index 4f41333..18d399a 100644 --- a/lib/dependor/instantiator.rb +++ b/lib/dependor/instantiator.rb @@ -20,9 +20,9 @@ def new(klass_name, overwrites = {}) klass.new(args) end - def get_class(klass_name) + def get_class(klass_name, overwrites = {}) klass = @class_lookup.lookup(klass_name) - SubclassBuilder.subclass(klass, @injector) + SubclassBuilder.subclass(klass, @injector, overwrites) end def method_missing(name, *args, &block) diff --git a/lib/dependor/subclass_builder.rb b/lib/dependor/subclass_builder.rb index 4bbeb67..c152180 100644 --- a/lib/dependor/subclass_builder.rb +++ b/lib/dependor/subclass_builder.rb @@ -1,12 +1,19 @@ module Dependor class SubclassBuilder - def self.subclass(klass, injector) + def self.get_dependency(name, injector, overwrites) + return overwrites.fetch(name) { @injector[name] } + end + + def self.subclass(klass, injector, overwrites = {}) return klass unless klass.respond_to?(:class_takes) Class.new(klass) do - klass.class_takes.each do |dependency| - define_singleton_method dependency do - injector[dependency] + klass.class_takes.each do |name| + define_singleton_method name do + unless instance_variable_get("@#{name}") + instance_variable_set("@#{name}", overwrites.fetch(name) { injector[name] }) + end + instance_variable_get("@#{name}") end end end diff --git a/spec/features/automagic_injection_spec.rb b/spec/features/automagic_injection_spec.rb index 7ab25bf..d9d0e12 100644 --- a/spec/features/automagic_injection_spec.rb +++ b/spec/features/automagic_injection_spec.rb @@ -33,6 +33,10 @@ class Crown class MagicalSword < Sword extend Takes(:name) end + + class Kingdom + extend ClassTakes(:king, :name) + end end end @@ -61,6 +65,7 @@ class MagicalSword < Sword excalibur { new(:MagicalSword, name: "Excalibur") } king { arthur } knights { [lancelot, galahad] } + kingdom { get_class(:Kingdom, name: "Far Far Away") } end } @@ -76,6 +81,14 @@ class MagicalSword < Sword expect(registry[:king]).to equal(registry[:arthur]) end + it "allows class injections" do + expect(registry[:kingdom]).to be_an_instance_of(Class) + end + + it "allows for overrides when injecting classes" do + expect(registry[:kingdom].name).to eq("Far Far Away") + end + it "makes objects singletons by default" do first_camelot = registry[:camelot] second_camelot = registry[:camelot]