加入我们,或者,欢迎回来。
您需要 登录 才可以下载或查看,没有帐号?注册会员
x
当年写了一个用class_eval的笨蛋Monkeypacth嗯
于是这次发到外站之后果断有触手帮忙改了>_<,果然我就是个渣
于是把最终版本放这里吧:
#=============================================================================== # Monkeypatch v 0.5 by BakaCoder aka XXX # rewritten by IceDragon #=============================================================================== # monkeypatch <method_name (sym)> (&block) #=============================================================================== proc do # Example class Scene_Base patch :initialize do puts "A Scene has been initialized!" end patch :initialize, :before do puts "Scene #{self.class.name} initializing" end end class Something def sum 1 + 1 end patch :sum, :chain do |oldsum| oldsum + 1 end end # End end module MonkeyPatch def monkeypatch(sym, pos=:after, &block) meth = instance_method(sym) # original method define_method(sym, &block) meth2 = instance_method(sym) # alias method case pos when :after define_method(sym) do |*a, &b| meth.bind(self).call(*a, &b) meth2.bind(self).call(*a, &b) end when :before define_method(sym) do |*a, &b| meth2.bind(self).call(*a, &b) meth.bind(self).call(*a, &b) end when :chain define_method(sym) do |*a, &b| meth2.bind(self).call(meth.bind(self).call(*a, &b), *a, &b) end end end alias :patch :monkeypatch end class Module include MonkeyPatch end
#===============================================================================
# Monkeypatch v 0.5 by BakaCoder aka XXX
# rewritten by IceDragon
#===============================================================================
# monkeypatch <method_name (sym)> (&block)
#===============================================================================
proc do
# Example
class Scene_Base
patch :initialize do
puts "A Scene has been initialized!"
end
patch :initialize, :before do
puts "Scene #{self.class.name} initializing"
end
end
class Something
def sum
1 + 1
end
patch :sum, :chain do |oldsum|
oldsum + 1
end
end
# End
end
module MonkeyPatch
def monkeypatch(sym, pos=:after, &block)
meth = instance_method(sym) # original method
define_method(sym, &block)
meth2 = instance_method(sym) # alias method
case pos
when :after
define_method(sym) do |*a, &b|
meth.bind(self).call(*a, &b)
meth2.bind(self).call(*a, &b)
end
when :before
define_method(sym) do |*a, &b|
meth2.bind(self).call(*a, &b)
meth.bind(self).call(*a, &b)
end
when :chain
define_method(sym) do |*a, &b|
meth2.bind(self).call(meth.bind(self).call(*a, &b), *a, &b)
end
end
end
alias :patch :monkeypatch
end
class Module
include MonkeyPatch
end
使用说明啥的基本不需要了,反正就是
patch :method_name do
#TODO
end
不过据说有奇怪的bug._.? |