Rails 缓存引起的 Undefined Class/Module 有什么优雅的解决方法?

suupic · April 13, 2012 · Last by hooopo replied at September 12, 2012 · 4151 hits

用 memcache 缓存模型对象后,在开发环境可能会遇到 ArgumentError: undefined class/module 的问题 google 了一圈,基本上只有这个发表于 07 年的解决方案

before_filter  :preload_models

def preload_models()
  Model1
  Model2
  ...
  ...
  ...
  Model9
end

不知还有没有更好的处理方法?

我的方案,写一个 initializer 来 patch Marshal 的 load 方法:

module Marshal
  class << self
    def load_with_constantize(value)
      begin
        Marshal.load_without_constantize value
      rescue ArgumentError => e
        _, class_name = *(/undefined class\/module (\w+)/.match(e.message))
        raise if !class_name
        class_name.constantize
        Marshal.load value
      end
    end
    alias_method_chain :load, :constantize
  end
end

#1 楼 @quakewang 谢谢,原来可以这样解决

#1 楼 @quakewang 题外话:现在不流行使用 alias_method_chain 了。rails-3 中使用 alias_method_chain 已经很少了,都是在模块中重写方法,必要时用 super 调用原来的方法,然后 include 到类中。 :)

自己写了一个序列化/反序列化 AR 对象的方法,没有这个问题了,并且速度有提升。。 最重要的是不会把关联缓存/dirty 属性等存到缓存里。 https://gist.github.com/3447628

You need to Sign in before reply, if you don't have an account, please Sign up first.