ruby – alias_method和class_methods不混合?

前端之家收集整理的这篇文章主要介绍了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
原文链接:https://www.f2er.com/ruby/273170.html

猜你在找的Ruby相关文章