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を操作しようとします。モジュールに名前が付けられたインスタンス メソッドがないため、失敗します。getCache

クラスメソッド ( のメタクラスのメソッド)にエイリアスを設定する必要があるため、次の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 に答える