has_cache.rb 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # Copyright (C) 2012-2021 Zammad Foundation, http://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. true
  12. end
  13. def cache_delete
  14. cache_keys = []
  15. # delete by id with attributes_with_association_ids caches
  16. cache_keys.push "#{self.class}::aws::#{id}"
  17. # delete caches of lookup_keys (e.g. id, name, email, login, number)
  18. self.class.lookup_keys.each do |lookup_key|
  19. cache_keys.push "#{self.class}::#{self[lookup_key]}"
  20. next if !saved_changes? || !saved_changes.key?(lookup_key)
  21. obsolete_lookup_key = saved_changes[lookup_key][0]
  22. cache_keys.push "#{self.class}::#{obsolete_lookup_key}"
  23. end
  24. cache_keys.each do |key|
  25. Cache.delete(key)
  26. end
  27. true
  28. end
  29. # methods defined here are going to extend the class, not the instance of it
  30. class_methods do
  31. def cache_set(data_id, data)
  32. key = "#{self}::#{data_id}"
  33. # cache for 4 hours max to lower impact of race conditions
  34. Cache.write(key, data, expires_in: 4.hours)
  35. end
  36. def cache_get(data_id)
  37. key = "#{self}::#{data_id}"
  38. Cache.read(key)
  39. end
  40. end
  41. end