Created
October 15, 2011 19:14
-
-
Save renato-zannon/1290010 to your computer and use it in GitHub Desktop.
Inject alternate implementation
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
module Inject | |
class Injector | |
def self.inject(*args, &block) | |
options = args.last.kind_of?(Hash) ? args.pop : {} | |
target = options[:receiver] || block.binding.eval("self") | |
modules = args | |
modules.each { |mod| mod.before_inject(target) if mod.respond_to?(:before_inject)} | |
return_value = new(modules).inject_into(target, &block) | |
modules.each { |mod| mod.after_deject(target) if mod.respond_to?(:after_deject) } | |
return return_value | |
end | |
def initialize(modules) | |
@modules = modules | |
end | |
def inject_into(target, &block) | |
if block.arity == 1 | |
block.call extended(target) | |
else | |
extensible_target = target.respond_to?(:binding) ? target.binding : target | |
extended(extensible_target).instance_eval(&block) | |
end | |
end | |
private | |
def extended(object) | |
@modules.inject(object.clone) { |obj, mod| obj.extend(mod) } | |
end | |
end | |
end | |
def Inject(*args, &blk) | |
Inject::Injector.inject(*args, &blk) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment