Created
March 12, 2015 22:19
-
-
Save fahim/8dcffbb24e946922d8fe to your computer and use it in GitHub Desktop.
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 CachedAttributes | |
# | |
# CachedAttributes creates convenience class methods to save DB query | |
# Retailer.allow_alcohol?(1) == Retailer.find(1).allow_alcohol | |
# | |
# class Retailer | |
# include CachedAttributes | |
# cache_boolean :allow_alcohol | |
# end | |
# | |
def cache_boolean(attribute) | |
define_singleton_method("#{attribute}?") do |object_id| | |
Rails.cache.fetch("cache-boolean:#{self.name.downcase}-#{object_id}-#{attribute}", expires_in: 1.week, race_condition_ttl: 10) do | |
self.find(object_id).send("#{attribute}?") | |
end | |
end | |
define_method("clear_#{attribute}_cache") do | |
Rails.cache.delete("cache-boolean:#{self.class.name.downcase}-#{self.id}-#{attribute}") | |
end | |
after_save "clear_#{attribute}_cache", if: :"#{attribute}_changed?" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment