free_mutant/lib/mutant/require_highjack.rb

65 lines
1.1 KiB
Ruby
Raw Normal View History

2014-04-04 08:38:06 -04:00
module Mutant
# Require highjack
class RequireHighjack
include Concord.new(:target, :callback)
# Return original method
#
# @return [#call]
#
# @api private
#
attr_reader :original
# Run block with highjacked require
#
# @return [self]
#
2014-06-28 16:52:47 -04:00
# @api private
2014-04-04 08:38:06 -04:00
#
def run
infect
yield
self
ensure
desinfect
end
# Infect kernel with highjack
#
# @return [self]
#
2014-06-28 16:52:47 -04:00
# @api private
2014-04-04 08:38:06 -04:00
#
def infect
callback = @callback
@original = target.method(:require)
target.module_eval do
undef :require
define_method(:require) do |logical_name|
callback.call(logical_name)
end
module_function :require
end
end
# Imperfectly desinfect kernel from highjack
#
# @return [self]
#
# @api private
#
def desinfect
original = @original
target.module_eval do
undef :require
define_method(:require) do |logical_name|
original.call(logical_name)
end
module_function :require
end
end
end # RequireHighjack
end # Mutant