2010-05-27 9 views
13

Ho cercato di armeggiare con un modulo Cache globale, ma non riesco a capire perché questo non funziona.alias_method e class_methods non si mescolano?

Qualcuno ha qualche suggerimento?

Questo è l'errore:

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

... generato da questo codice:

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 

risposta

17

Le chiamate verso alias_method tenterà di operare su esempio metodi. Non esiste un metodo di istanza denominato get nel modulo Cache, quindi non riesce.

Perché si vuole alias classe metodi (metodi sul metaclasse di Cache), che avrebbe dovuto fare qualcosa di simile:

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

Non è necessario l'intera classe 'Cache.module_eval fare < Chuck

+0

@Chuck, buon punto; aggiornato! – molf

Problemi correlati