has_cache.rb 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # Copyright (C) 2012-2016 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. keys = []
  15. # delete by id caches
  16. keys.push "#{self.class}::#{id}"
  17. # delete by id with attributes_with_association_ids caches
  18. keys.push "#{self.class}::aws::#{id}"
  19. # delete by name caches
  20. if self[:name]
  21. keys.push "#{self.class}::#{name}"
  22. end
  23. # delete by login caches
  24. if self[:login]
  25. keys.push "#{self.class}::#{login}"
  26. end
  27. keys.each do |key|
  28. Cache.delete(key)
  29. end
  30. # delete old name / login caches
  31. if saved_changes?
  32. if saved_changes.key?('name')
  33. name = saved_changes['name'][0]
  34. key = "#{self.class}::#{name}"
  35. Cache.delete(key)
  36. end
  37. if saved_changes.key?('login')
  38. name = saved_changes['login'][0]
  39. key = "#{self.class}::#{name}"
  40. Cache.delete(key)
  41. end
  42. end
  43. true
  44. end
  45. # methods defined here are going to extend the class, not the instance of it
  46. class_methods do
  47. def cache_set(data_id, data)
  48. key = "#{self}::#{data_id}"
  49. Cache.write(key, data)
  50. end
  51. def cache_get(data_id)
  52. key = "#{self}::#{data_id}"
  53. Cache.get(key)
  54. end
  55. end
  56. end