Skip to content

Instantly share code, notes, and snippets.

@endash
Last active October 11, 2015 13:11
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 endash/14b138e57568fc776ceb to your computer and use it in GitHub Desktop.
Save endash/14b138e57568fc776ceb to your computer and use it in GitHub Desktop.
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