代码之家  ›  专栏  ›  技术社区  ›  Daniel

别名\方法和类\方法不混合?

  •  13
  • Daniel  · 技术社区  · 14 年前

    我一直在尝试修补一个全局缓存模块,但我不明白为什么这不起作用。

    有人有什么建议吗?

    这是错误:

    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
    
    1 回复  |  直到 10 年前
        1
  •  17
  •   molf    14 年前

    呼唤 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