Skip to content

Instantly share code, notes, and snippets.

@svyatogor
Created May 24, 2011 15:12
Show Gist options
  • Save svyatogor/988887 to your computer and use it in GitHub Desktop.
Save svyatogor/988887 to your computer and use it in GitHub Desktop.
mongoid per id cache
module Mongoid #:nodoc:
module Cache
extend ActiveSupport::Concern
included do
class << self
alias_method :original_find, :find
def find_with_cache(*args)
if args.length == 1 and (args[0].is_a? BSON::ObjectId or args[0].is_a? String)
Rails.cache.fetch("#{self.name}::#{args[0].to_s}") {find_without_cache *args}
else
find_without_cache *args
end
end
alias_method_chain :find, :cache
end
before_update :invalidate_cache
before_destroy :invalidate_cache
end
def InstanceMethods
def invalidate_cache
self.class.query_cache.delete id.to_s
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment