Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Inject alternate implementation
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