簡體   English   中英

alias_method和class_methods不混合嗎?

[英]alias_method and class_methods don't mix?

我一直在嘗試修改全局Cache模塊,但是我不知道為什么這不起作用。

有沒有人有什么建議?

這是錯誤:

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的調用將嘗試對實例方法進行操作。 在您的Cache模塊中沒有名為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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM