Skip to content

Commit

Permalink
add overwrites for class injections
Browse files Browse the repository at this point in the history
  • Loading branch information
kustosz committed Sep 12, 2014
1 parent 2b22909 commit 8bc7e2d
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 6 deletions.
1 change: 1 addition & 0 deletions lib/dependor/core_ext.rb
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
Object.extend Dependor::TakesExt
Object.extend Dependor::ClassTakesExt
Transient = Dependor::Transient
4 changes: 2 additions & 2 deletions lib/dependor/instantiator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
15 changes: 11 additions & 4 deletions lib/dependor/subclass_builder.rb
Original file line number Diff line number Diff line change
@@ -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
Expand Down
13 changes: 13 additions & 0 deletions spec/features/automagic_injection_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ class Crown
class MagicalSword < Sword
extend Takes(:name)
end

class Kingdom
extend ClassTakes(:king, :name)
end
end
end

Expand Down Expand Up @@ -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
}

Expand All @@ -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]
Expand Down

0 comments on commit 8bc7e2d

Please sign in to comment.