Skip to content

Instantly share code, notes, and snippets.

@caironoleto
Created July 14, 2010 18:37
Show Gist options
  • Save caironoleto/475819 to your computer and use it in GitHub Desktop.
Save caironoleto/475819 to your computer and use it in GitHub Desktop.
module ActiveSupport
module Cache
class SmartMemCacheStore < MemCacheStore
alias_method :orig_read, :read
alias_method :orig_write, :write
def read(key, options = nil)
lock_expires_in = options.delete(:lock_expires_in) if !options.nil?
lock_expires_in ||= 30
response = orig_read(key, options)
return nil if response.nil?
data, expires_at = response
if Time.now > expires_at && !orig_read("lock_#{key}").present?
orig_write("lock_#{key}", true, :expires_in => lock_expires_in)
return nil
else
data
end
end
def write(key, value, options = nil)
expires_delta = options.delete(:expires_delta) if !options.nil?
expires_delta ||= 300
expires_at = Time.now + expires_delta
package = [value, expires_at]
orig_write(key, package, options)
delete("lock_#{key}")
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment