13

我一直在尝试修改全局缓存模块,但我无法弄清楚为什么这不起作用。

有没有人有什么建议?

这是错误:

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
4

1 回答 1

17

调用alias_method将尝试对实例方法进行操作。get您的模块中没有命名实例方法Cache,因此它失败了。

因为您想为方法(元类上的方法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
于 2010-05-27T21:31:46.633 回答