Skip to content

Instantly share code, notes, and snippets.

@ne-sachirou
Last active August 29, 2015 14:19
Show Gist options
  • Save ne-sachirou/722c84c0d43d1f221fe2 to your computer and use it in GitHub Desktop.
Save ne-sachirou/722c84c0d43d1f221fe2 to your computer and use it in GitHub Desktop.
DI (IoC) container in Ruby.
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