2010-05-27 11 views
13

J'ai essayé de bricoler avec un module de cache global, mais je n'arrive pas à comprendre pourquoi cela ne fonctionne pas.alias_method et class_methods ne se mélangent pas?

Quelqu'un a-t-il des suggestions?

C'est l'erreur:

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

... généré par ce code:

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 

Répondre

17

Les appels à alias_method tenteront d'opérer sur exemple méthodes. Il n'y a pas de méthode d'instance nommée get dans votre module Cache, donc elle échoue.

Parce que vous souhaitez créer un alias classe méthodes (méthodes sur la métaclasse de Cache), vous devez faire quelque chose comme:

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

Vous n'avez pas besoin toute 'Cache.module_eval faire classe < Chuck

+0

@Chuck, bon point; actualisé! – molf