Created
August 6, 2008 20:09
-
-
Save brianjlandau/4268 to your computer and use it in GitHub Desktop.
Allows defining named scopes you wish to have cached.
This file contains 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
module ActiveRecord | |
module CacheScopes | |
def self.included(base) | |
base.extend(ClassMethods) | |
end | |
module ClassMethods | |
def cache_scopes(scopes) | |
class_eval "@@finder_caches ||= []" | |
cattr_accessor :finder_caches | |
scopes.each do |name, finder| | |
name = name.to_s | |
finder = finder.to_s | |
cattr_accessor "#{name}_cache".to_sym | |
class_eval <<-EOV | |
@@finder_caches << :#{name} | |
def self.#{name} | |
unless (%W(production stage).include? RAILS_ENV) && ActionController::Base.perform_caching | |
@@#{name}_cache = self.#{finder} | |
else | |
@@#{name}_cache ||= self.#{finder} | |
end | |
end | |
EOV | |
end | |
after_save :reset_cached_finders | |
after_destroy :reset_cached_finders | |
class_eval <<-EOV | |
def self.reset_cached_finders | |
@@finder_caches.each do |finder_cache| | |
self.send "\#{finder_cache}_cache=".to_sym, nil | |
end | |
end | |
protected | |
def reset_cached_finders | |
self.class.reset_cached_finders | |
end | |
EOV | |
end | |
end | |
end | |
end | |
ActiveRecord::Base.send :include, ActiveRecord::CacheScopes | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment