Created
November 26, 2012 03:10
-
-
Save dcolthorp/4146425 to your computer and use it in GitHub Desktop.
Simply Ruby Dependency Injection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Context | |
def initialize() | |
@cache = {} | |
end | |
def [](klass) | |
if @cache.has_key?(klass) | |
@cache[klass] | |
else | |
inst = klass.instantiateForContext self | |
@cache[klass] = inst | |
inst.injectWithContext self | |
inst | |
end | |
end | |
def new(klass) | |
inst = klass.instantiateForContext(self) | |
inst.injectWithContext self | |
inst | |
end | |
def []=(key, value) | |
@cache[key] = value | |
end | |
end | |
class Class | |
def instantiateForContext(context) | |
new | |
end | |
end | |
class Object | |
def injectWithContext(context) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Foo | |
def injectWithContext(context) | |
@bar = context[Bar] | |
end | |
#... | |
end | |
class Bar | |
# no dependencies | |
# ... | |
end | |
class Baz | |
def injectWithContext(context) | |
@foo = context[Foo] | |
@bar = context[Bar] | |
end | |
#... | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class NSNotificationCenter | |
def self.instantiateForContext(context) | |
defaultCenter | |
end | |
end | |
class PFInstallation | |
def self.instantiateForContext(context) | |
PFInstallation.currentInstallation | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment