Skip to content

Instantly share code, notes, and snippets.

@darkhelmet
Created September 15, 2009 03:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darkhelmet/187098 to your computer and use it in GitHub Desktop.
Save darkhelmet/187098 to your computer and use it in GitHub Desktop.
class Cache < ActiveRecord::Base
serialize :value
def self.get(key, max_age = 1.hour)
item = Cache.first(:conditions => { :key => key })
if block_given?
if item.nil? || item.updated_at < max_age.ago
begin
value = yield
Cache.put(key,value)
value
rescue Exception => e
p e.message
item.nil? ? nil : item.value
end
else
item.value
end
else
item.nil? ? nil : item.value
end
end
def self.put(key,value)
c = Cache.find_or_create_by_key(key)
c.value = value
c.save
c.touch
end
def self.purge(key)
items = key.nil? ? Cache.all : Cache.all(:conditions => { :key => key })
items.each do |item|
item.destroy
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment