質問

私はグローバルなキャッシュモジュールをいじくり回そうとしてきましたが、なぜこれが機能していないのかわかりません。

誰かが何か提案はありますか?

これはエラーです:

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 モジュールなので、失敗します。

エイリアスしたいからです クラス メソッド(メタクラスのメソッド 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帰属
所属していません StackOverflow
scroll top