Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save teeparham/994666 to your computer and use it in GitHub Desktop.
Save teeparham/994666 to your computer and use it in GitHub Desktop.
simple active record caching
# for some reason active record doesn't include a simple way to serialize to
# cache. this simple trick will take you far
#
# usage:
#
# user = User.find(id)
#
# key = user.to_cache
#
# user = User.from_cache(key)
#
# note: AR provides a cache_key method
# http://apidock.com/rails/ActiveRecord/Base/cache_key
class ActiveRecord::Base
def self.from_cache(key)
attributes = Rails.cache.read(key)
instantiate(attributes) if attributes
end
def to_cache
cache_key if Rails.cache.write(cache_key, attributes)
end
end
@squidarth
Copy link

Awesome thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment