Created
December 3, 2017 22:16
-
-
Save jwhiteman/6be7692627d4de35fa6edf53d4681389 to your computer and use it in GitHub Desktop.
Dumb DI container
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 DIContainer | |
def configure | |
yield self | |
end | |
def method_missing(key, val) | |
if key =~ /=$/ | |
key = key.to_s.chop | |
(class << self; self; end).class_eval do | |
attr_accessor key | |
end | |
__send__(:"#{key}=", val) | |
else | |
super | |
end | |
end | |
end | |
def configure | |
Container.new.tap do |c| | |
yield c | |
c.freeze if freeze | |
end | |
end | |
module A | |
extend self | |
def shout(foo: DI.foo) | |
foo.shout | |
end | |
end | |
module Foo | |
extend self | |
def shout;"the real foo";end | |
end | |
module FakeFoo | |
extend self | |
def shout;"fake foo!";end | |
end | |
DI = configure do |c| | |
c.foo = Foo | |
end | |
A.shout | |
DI.configure do |c| | |
c.foo = FakeFoo | |
end | |
A.shout |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment