-
-
Save teeparham/994666 to your computer and use it in GitHub Desktop.
simple active record caching
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome thanks