alias_method 和 class_methods 不能混合使用?
我一直在尝试修补全局缓存模块,但我不明白为什么这不起作用。
有人有什么建议吗?
这是错误:
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
I've been trying to tinker with a global Cache module, but I can't figure out why this isn't working.
Does anyone have any suggestions?
This is the error:
NameError: undefined method `get' for module `Cache'
from (irb):21:in `alias_method'
... generated by this code:
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对
alias_method
的调用将尝试对实例方法进行操作。您的Cache
模块中没有名为get
的实例方法,因此失败。因为您想要为 class 方法(
Cache
的元类上的方法)添加别名,所以您必须执行以下操作:The calls to
alias_method
will attempt to operate on instance methods. There is no instance method namedget
in yourCache
module, so it fails.Because you want to alias class methods (methods on the metaclass of
Cache
), you would have to do something like: