Last active
October 11, 2015 13:11
-
-
Save endash/14b138e57568fc776ceb to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Container | |
def initialize injections | |
@injections = injections | |
@resolved = {} | |
end | |
def have? token | |
!get_injection(token).nil? | |
end | |
def get token | |
lookup(token) | |
end | |
private | |
def get_injection token | |
token_tree = token.split(".").map(&:to_sym) | |
token_tree.reduce(@injections) do |current_level, token| | |
current_level && current_level[token] | |
end | |
end | |
def lookup token | |
token = token.to_s | |
return @resolved[token] if @resolved[token] | |
injection = get_injection(token) | |
if injection.is_a? Proc | |
@resolved[token] = injection.call | |
elsif injection.is_a? Class | |
@resolved[token] = injection.new | |
elsif injection.is_a? Array | |
klass_or_proc = injection.first | |
resolved_dependencies = injection.drop(1).map { |d| lookup(d) } | |
if klass_or_proc.respond_to?(:call) | |
@resolved[token] = klass_or_proc.call(*resolved_dependencies) | |
else | |
@resolved[token] = klass_or_proc.new(*resolved_dependencies) | |
end | |
else | |
@resolved[token] = injection | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment