Memcached as an object store in Rails

I use Memcached as an object store with my Rails application, where I store search results that are User objects in memcached

Now, when I retrieve the data, I get Memcached Undefined Class / module error. I found a solution to this problem in this blog.

http://www.philsergi.com/2007/06/rails-memcached-undefinded-classmodule.html

before_filter :preload_models def preload_models Model1 Model2 end 

which recommends preloading models before starting work. I would like to know if there is a more elegant solution to this problem and if there are any drawbacks to using the preload technique.

Thanks in advance

+7
ruby-on-rails memcached models eager-loading
source share
2 answers

I also had this problem, and I think I came up with a good solution.

You can overwrite the fetch method and save the error and load the correct constants.

 module ActiveSupport module Cache class MemCacheStore # Fetching the entry from memcached # For some reason sometimes the classes are undefined # First rescue: trying to constantize the class and try again. # Second rescue, reload all the models # Else raise the exception def fetch(key, options = {}) retries = 2 begin super rescue ArgumentError, NameError => exc if retries == 2 if exc.message.match /undefined class\/module (.+)$/ $1.constantize end retries -= 1 retry elsif retries == 1 retries -= 1 preload_models retry else raise exc end end end private # There are errors sometimes like: undefined class module ClassName. # With this method we re-load every model def preload_models #we need to reference the classes here so if coming from cache Marshal.load will find them ActiveRecord::Base.connection.tables.each do |model| begin "#{model.classify}".constantize rescue Exception end end end end end end 
+8
source share

After going through this today, I managed to come up with a more subtle solution that should work for all classes.

 Rails.cache.instance_eval do def fetch(key, options = {}, rescue_and_require=true) super(key, options) rescue ArgumentError => ex if rescue_and_require && /^undefined class\/module (.+?)$/ =~ ex.message self.class.const_missing($1) fetch(key, options, false) else raise ex end end end 

I donโ€™t know why [MemCacheStore] doesnโ€™t have the [MemCacheStore.const_missing] method, and everything calls the Rails-y call in normal mode. But that should imitate that!

Greetings

Chris

+5
source share

All Articles