Question

J'ai essayé de bricoler avec un module de cache global, mais je ne peux pas comprendre pourquoi cela ne fonctionne pas.

Quelqu'un at-il des suggestions?

Ceci 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
Était-ce utile?

La solution

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

Parce que vous voulez alias classe méthodes (méthodes sur la méta-classe 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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top