0

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

Wallace
  • 151
  • 1
  • 9
  • 2
    I'd bet on autoloading / load order. Maybe your class is getting loaded before one from activesupport. And instead of patching a class, you create it. And then the AS version won't be loaded. – Sergio Tulentsev Apr 04 '19 at 21:26
  • You should do `Rails.cache.fetch(CACHE_KEY) { all.to_a }` instead. `Rails.cache.fetch(CACHE_KEY) { all }` doesn't actually cache anything useful since `all` is an AR object, and _not_ an array. May not be related to your issue, but important if you want caching to be effective. – Glyoko Apr 04 '19 at 21:45
  • @SergioTulentsev if so that make lot of senses, any way can see the order of autoloading? i put it under initializer folder, maybe i miss adding something related to the order but i don't know it – Wallace Apr 04 '19 at 21:46
  • @Glyoko thanks a lot, but that's someone else code i don't want to touch – Wallace Apr 04 '19 at 21:47
  • What is the actual purpose of this monkey patch? – lacostenycoder Apr 05 '19 at 00:35
  • @lacostenycoder i was thinking about logging every key that server is reading/fetching, count them all, then find which key are top ones so that we know where to optimize it – Wallace Apr 05 '19 at 15:13

0 Answers0