has_cache.rb 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. module ApplicationModel::HasCache
  3. extend ActiveSupport::Concern
  4. included do
  5. before_create :cache_delete
  6. after_commit :cache_delete
  7. end
  8. def cache_update(other)
  9. cache_delete if respond_to?(:cache_delete)
  10. other.cache_delete if other.respond_to?(:cache_delete)
  11. ActiveSupport::CurrentAttributes.clear_all
  12. true
  13. end
  14. def cache_delete
  15. cache_keys = []
  16. # delete by id with attributes_with_association_ids caches
  17. cache_keys.push "#{self.class}::aws::#{id}"
  18. # delete caches of lookup_keys (e.g. id, name, email, login, number)
  19. self.class.lookup_keys.each do |lookup_key|
  20. cache_keys.push "#{self.class}::#{self[lookup_key]}"
  21. next if !saved_changes? || !saved_changes.key?(lookup_key)
  22. obsolete_lookup_key = saved_changes[lookup_key][0]
  23. cache_keys.push "#{self.class}::#{obsolete_lookup_key}"
  24. end
  25. cache_keys.each do |key|
  26. Cache.delete(key)
  27. end
  28. true
  29. end
  30. # methods defined here are going to extend the class, not the instance of it
  31. class_methods do
  32. def cache_set(data_id, data)
  33. key = "#{self}::#{data_id}"
  34. # cache for 4 hours max to lower impact of race conditions
  35. Cache.write(key, data, expires_in: 4.hours)
  36. end
  37. def cache_get(data_id)
  38. key = "#{self}::#{data_id}"
  39. Cache.read(key)
  40. end
  41. end
  42. end