Skip to content

Instantly share code, notes, and snippets.

@sunaot
Last active August 29, 2015 14:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunaot/1b15d0c6aa82ed91740b to your computer and use it in GitHub Desktop.
Save sunaot/1b15d0c6aa82ed91740b to your computer and use it in GitHub Desktop.
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