gpt4 book ai didi

ruby - alias_method 和 class_methods 不混合?

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

我一直在尝试修补全局缓存模块,但我不明白为什么它不起作用。

有人有什么建议吗?

这是错误:

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 的调用将尝试对实例 方法进行操作。 Cache 模块中没有名为 get 的实例方法,因此失败。

因为你想给 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

关于ruby - alias_method 和 class_methods 不混合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2925016/

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