has_cache.rb 1.6 KB

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