Teflon Ted
Teflon Ted

Reputation: 8856

How can I force Rails (2.3.x) MemCacheStore to read a value from the server?

Long story short: I have some controller logic that requests a value from the cache X times, expecting to get a different value on subsequent requests if it has in fact changed on the cache server in between cache requests (this is all within the context of a single HTTP request).

However it seems that Rails MemCacheStore wraps itself with Strategy::LocalCache so no matter how many times I request the value it will always return the first value it pulled from the server regardless if that value has changed on the server in between requests.

I was hoping there was some undocumented :force option for the read() method, but no such luck.

So my next hope was to monkey-patch it somehow to get what I needed but I'm stumped there.

Any advice?

Upvotes: 2

Views: 240

Answers (2)

Teflon Ted
Teflon Ted

Reputation: 8856

Got it working (thanks to @KandadaBoggu suggestion) by back-porting and monkey-patching the bypass_local_cache feature from activesupport 3.0

module ActiveSupport
  module Cache
    module Strategy
      module LocalCache
        protected
        def bypass_local_cache
          save_cache = Thread.current[thread_local_key]
          begin
            Thread.current[thread_local_key] = nil
            yield
          ensure
            Thread.current[thread_local_key] = save_cache
          end
        end
      end
    end
  end
end

Upvotes: 2

Harish Shetty
Harish Shetty

Reputation: 64363

I am not certain if this will work but worth a try:

cache.send(:bypass_local_cache) { cache.read("bar")}

Where bar is the key you are trying to access.

Note: bypass_local_cache is a private method.

Upvotes: 1

Related Questions