我一直在尝试修补全局缓存模块,但我不明白为什么这不起作用。
有没有人有什么建议?
这是错误:
NameError: undefined method `get' for module `Cache'
from (irb):21:in `alias_method'
...由这段代码生成:
module Cache
def self.get
puts "original"
end
end
module Cache
def self.get_modified
puts "New get"
end
end
def peek_a_boo
Cache.module_eval do
# make :get_not_modified
alias_method :get_not_modified, :get
alias_method :get, :get_modified
end
Cache.get
Cache.module_eval do
alias_method :get, :get_not_modified
end
end
# test first round
peek_a_boo
# test second round
peek_a_boo
致电alias_method
将尝试操作instance方法。没有名为的实例方法get
在你的Cache
模块,所以失败。
因为你想别名class方法(元类上的方法Cache
),你将不得不做类似的事情:
class << Cache # Change context to metaclass of Cache
alias_method :get_not_modified, :get
alias_method :get, :get_modified
end
Cache.get
class << Cache # Change context to metaclass of Cache
alias_method :get, :get_not_modified
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)