Skip to content

Instantly share code, notes, and snippets.

@kusakari
Created March 30, 2011 09:06
Show Gist options
  • Save kusakari/894100 to your computer and use it in GitHub Desktop.
Save kusakari/894100 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
require 'digest/sha1'
require 'db_cache'
module ActsAsCached
module ClassMethods
def acts_as_cached(options = {})
extend RecordCache
end
end
module RecordCache
def get_cache(key=nil, &block)
return nil if key.nil?
dkey = digest_key(key)
if rs = autoload_missing_constants { DBCache.get(dkey) }
return rs
end
if block_given?
if rs = yield
DBCache.set(dkey, rs)
return rs
end
end
return nil
end
def autoload_missing_constants
begin
yield
rescue ArgumentError => error
lazy_load ||= Hash.new { |hash, hash_key| hash[hash_key] = true; false }
if error.to_s[/undefined class|referred/] && !lazy_load[error.to_s.split.last.sub(/::$/, '').constantize]
retry
else
raise error
end
end
end
def set_cache(key, rs)
return DBCache.set(digest_key(key), rs)
end
def expire_cache(key)
return DBCache.delete(digest_key(key))
end
def digest_key(key)
case key
when Array
key = key.flatten.join('-')
else
key = key.to_s unless key.is_a?(String)
end
return Digest::SHA1.hexdigest("#{cache_name}:#{key}")
end
def cache_name
return respond_to?(:base_class) ? base_class.name : name
end
end
end
Object.send :extend, ActsAsCached::ClassMethods
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment