Skip to content

Instantly share code, notes, and snippets.

@dcolthorp
Created November 26, 2012 03:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcolthorp/4146425 to your computer and use it in GitHub Desktop.
Save dcolthorp/4146425 to your computer and use it in GitHub Desktop.
Simply Ruby Dependency Injection
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
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
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