Created
October 24, 2013 06:03
-
-
Save nthj/7132073 to your computer and use it in GitHub Desktop.
Expirable Concern for Rails
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
# Expirable is a module that lets you easily cache | |
# groups of records, either across an entire record: | |
# cache(Snippet) => cache(Snippet.cache_key) | |
# or, across a scope: | |
# cache(page.blocks) => cache(page.blocks.cache_key) | |
# | |
# Why not just use `maximum(:updated_at)`? | |
# Because it requires 2 queries: the total count, | |
# and the updated_at timestamp | |
# This method requires 0 queries, because we fetch | |
# everything via Memcached, then nuke it based on the | |
# after_save callbacks. | |
# | |
# Use this method when your data rarely, if ever, changes. | |
# This the regular updated_at timestamp when your data changes | |
# frequently, because the extra after_save callback slows your | |
# writes down. | |
module Concerns::Expirable | |
extend ActiveSupport::Concern | |
included do | |
after_destroy :clear_expirable_cache_key | |
after_save :clear_expirable_cache_key | |
after_touch :clear_expirable_cache_key | |
end | |
module ClassMethods | |
def cache_key | |
Rails.cache.fetch(expirable_cache_key) do | |
"#{count}-#{last_modified}" | |
end | |
end | |
alias etag cache_key | |
def expirable_cache_key | |
Array[name, :cache_key] | |
end | |
def last_modified | |
maximum(:updated_at).utc | |
end | |
end | |
protected | |
def clear_expirable_cache_key | |
Rails.cache.delete self.class.expirable_cache_key | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment