gpt4 book ai didi

ruby - 覆盖方法然后还原

转载 作者:数据小太阳 更新时间:2023-10-29 06:58:18 26 4
gpt4 key购买 nike

我正在尝试找到一种方法,我可以覆盖一个方法,做一些事情,然后在不留下任何工件的情况下恢复。

我已经使用 mocha 实现了这个,但显然这不会在生产应用程序中运行。请注意,新方法有参数,而旧方法没有。

例子如下

require 'rubygems'
require 'mocha'

class Example

def to_something
self.stubs(:attribs => other(1))
r = attribs_caller
self.unstub(:attribs)
r
end

def other(int)
{"other" => int }
end

def attribs_caller
attribs
end

def attribs
{"this" => 1 }
end

end

a1 = Example.new

puts a1.attribs_caller #=> this1
puts a1.to_something #=> other1
puts a1.attribs_caller #=> this1

最佳答案

class String
alias orig_reverse reverse
def reverse(n)
'fooled you. '*n
end
end

puts "ab".reverse(2)
#=> fooled you fooled you

# clean up:
class String
alias reverse orig_reverse
remove_method(:orig_reverse)
end

puts "ab".reverse #=> ba

关于ruby - 覆盖方法然后还原,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5734527/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com