Ruby   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ruby – 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

解决方法

对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

大佬总结

以上是大佬教程为你收集整理的ruby – alias_method和class_methods不混合?全部内容,希望文章能够帮你解决ruby – alias_method和class_methods不混合?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: