jeudi 4 avril 2019

Rails Monkey Patch alias_method cause no method error

I am trying to monkey patch rails Rails.cache.fetch/read method, and add my extra log on every fetch/read happened, but i got some other error that i can't google any answer.

here is my monkey patch code

module ActiveSupport
    module Cache
        class Store
            alias_method :old_fetch, :fetch
            alias_method :old_read, :read

            def fetch(name, options=nil)
                Rails.logger.info "Memcached Hotkey Fetching: #{name}"
                Rails.logger.info caller
                old_fetch(name, options)
            end

            def read(name, options=nil)
                Rails.logger.info "Memcached Hotkey Reading: #{name}"
                Rails.logger.info caller
                old_read(name, options)
            end
        end
    end
end

here is where travis busted

class B < ActiveRecord::Base
  def self.cache
    Rails.cache.fetch(CACHE_KEY, :expires_in => 1.hour) do
      all
    end
  end

there is code somewhere callingB.cache.each do |x| blablabla end

Error message:  You have a nil object when you didn't expect it! (NoMethodError),
You might have expected an instance of Array.
The error occurred while evaluating nil.each

the question is what am I doing in wrong way? i just monkey patch two methods under Store, but why it seems overwrite everything that's calling .cache

Aucun commentaire:

Enregistrer un commentaire