加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – alias_method和class_methods不混合?

发布时间:2020-12-16 20:20:17 所属栏目:百科 来源:网络整理
导读:我一直在努力修改一个全局缓存模块,但是我不知道为什么这不工作. 有没有人有什么建议? 这是错误: NameError: undefined method `get' for module `Cache' from (irb):21:in `alias_method' …由此代码生成: module Cache def self.get puts "original" en
我一直在努力修改一个全局缓存模块,但是我不知道为什么这不工作.

有没有人有什么建议?

这是错误:

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

因为你想要别名类方法(在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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读