Last active
August 29, 2015 14:19
-
-
Save ne-sachirou/722c84c0d43d1f221fe2 to your computer and use it in GitHub Desktop.
DI (IoC) container in Ruby.
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 Container | |
def initialize | |
@c = {} | |
@fac = {} | |
yield self | |
end | |
def [] k | |
@c[k] || (@fac[k] && @fac[k].call(self)) | |
end | |
def []= k, v | |
@c[k] = v | |
end | |
def factory k, &b | |
@fac[k] = b | |
end | |
end | |
class B | |
def initialize a; @a = a; end | |
end | |
c = Container.new do |c| | |
c[:a] = 42 | |
c[:b] = B.new c[:a] | |
c.factory(:b_new){|c| B.new c[:a] } | |
end | |
p c[:a] | |
p c[:b] | |
p c[:b] | |
p c[:b_new] | |
p c[:b_new] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment