Skip to content

Instantly share code, notes, and snippets.

@fahim
Created March 12, 2015 22:19
Show Gist options
  • Save fahim/8dcffbb24e946922d8fe to your computer and use it in GitHub Desktop.
Save fahim/8dcffbb24e946922d8fe to your computer and use it in GitHub Desktop.
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