Last active
August 29, 2015 14:13
-
-
Save sunaot/1b15d0c6aa82ed91740b to your computer and use it in GitHub Desktop.
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 Injectee | |
def hello | |
puts :hello | |
end | |
end | |
module DI | |
class Injector | |
def initialize(module_object) | |
@module = module_object | |
end | |
def to(var_name) | |
mod = if @module.instance_method(:initialize).arity == 0 | |
Module.new do | |
module_eval %Q| | |
def initialize | |
#{var_name.to_s} = #{"Injectee"}.new | |
super | |
end | |
| | |
end | |
else | |
Module.new do | |
module_eval %Q| | |
def initialize(*args, **params, &block) | |
#{var_name.to_s} = #{"Injectee"}.new | |
super | |
end | |
| | |
end | |
end | |
@module.instance_eval do | |
prepend mod | |
end | |
end | |
end | |
def self.included(mod) | |
mod.instance_variable_set(:@inject, Injector.new(mod)) | |
end | |
end | |
class Foo | |
include DI | |
@inject.to( :@hoge ) | |
def foo | |
@hoge.hello | |
end | |
end | |
Foo.new.foo #=> "hello" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment