Rails Monkey Patch alias_method不会导致方法错误

时间:2019-04-04 20:48:31

标签: ruby ruby-on-rails-3 alias-method

我正在尝试使用猴子Rails.cache.fetch/read跳线方法,并在每次获取/读取操作时添加我的额外日志,但是我遇到了其他错误,我无法在Google上找到任何答案。

这是我的猴子补丁代码

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

这是travis爆破的地方

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

某处有代码调用B.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

问题是我在用错误的方式做什么?我只是在Store下修补了两种方法,但是为什么它似乎覆盖了所有调用.cache的内容

0 个答案:

没有答案