2010-05-27 4 views
13

He estado tratando de jugar con un módulo global de caché, pero no puedo entender por qué esto no funciona.alias_method y class_methods no se mezclan?

¿Alguien tiene alguna sugerencia?

Este es el error:

NameError: undefined method `get' for module `Cache' 
    from (irb):21:in `alias_method' 

... generada por este código:

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 

Respuesta

17

Las llamadas a alias_method intentar operar en ejemplo métodos. No hay un método de instancia llamado get en su módulo Cache, por lo que falla.

Puesto que desea poner un alias clase métodos (métodos en la metaclase de Cache), que tendrían que hacer algo como:

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 
+3

Usted no necesita la clase entera 'Cache.module_eval hacer < Chuck

+0

@Chuck, buen punto; ¡actualizado! – molf

Cuestiones relacionadas