alias_method和class_methods不能混合使用吗? [英] alias_method and class_methods don't mix?

查看:88
本文介绍了alias_method和class_methods不能混合使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试修改全局Cache模块,但是我不知道为什么这不起作用.

I've been trying to tinker with a global Cache module, but I can't figure out why this isn't working.

有人有什么建议吗?

这是错误:

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

推荐答案

alias_method的调用将尝试在 instance 方法上进行操作.在Cache模块中没有名为get的实例方法,因此失败.

The calls to alias_method will attempt to operate on instance methods. There is no instance method named get in your Cache module, so it fails.

由于要为 class 方法(Cache的元类上的方法)加别名,因此您必须执行以下操作:

Because you want to alias class methods (methods on the metaclass of Cache), you would have to do something like:

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

这篇关于alias_method和class_methods不能混合使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆