2010-05-27 6 views
13

Próbowałem majstrować przy użyciu globalnego modułu pamięci podręcznej, ale nie mogę zrozumieć, dlaczego to nie działa.metody alias_method i class_methods nie mieszają się?

Czy ktoś ma jakieś sugestie?

Jest to błąd:

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

... generowane przez ten kod:

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 

Odpowiedz

17

Połączenia do alias_method będzie próbował działać na przykład metod. Nie ma metody instancji o nazwie get w swoim module Cache, więc nie powiedzie się.

Ponieważ chcesz alias klasę metod (metody na metaklasą z Cache), trzeba by zrobić coś takiego:

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

Nie potrzebujesz całego 'Cache.module_eval zrobić klasę < Chuck

+0

@Chuck, dobry punkt; zaktualizowany! – molf

Powiązane problemy