Skip to content

Instantly share code, notes, and snippets.

@dustMason
Created February 24, 2012 17:45
Show Gist options
  • Save dustMason/1902335 to your computer and use it in GitHub Desktop.
Save dustMason/1902335 to your computer and use it in GitHub Desktop.
CachedFinder Extension for ActiveRecord
require 'digest/sha1'
module Extensions
module CachedFinder
extend ActiveSupport::Concern
module ClassMethods
def cached(options = {})
options_hash = Digest::SHA1.hexdigest(options.to_s)
Rails.cache.fetch [self.class.to_s.underscore, options_hash].join('/'), :expires_in => 1.hour, :race_condition_ttl => 10 do
all options
end
end
def clear_cache(options = {})
options_hash = Digest::SHA1.hexdigest(options.to_s)
Rails.cache.delete [self.class.to_s.underscore, options_hash].join('/')
end
end
end
end
class Configurator < ActiveRecord::Base
include Extensions::CachedFinder
after_update :clear_cache
def self.get(label)
cached(:conditions => ['label = ?',label]).first.value
end
private
def clear_cache
self.class.clear_cache(:conditions => ['label = ?',label])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment