2017-01-31 17:13:45 +00:00
|
|
|
# Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
|
2017-05-02 15:21:13 +00:00
|
|
|
module ApplicationModel::HasCache
|
2017-01-31 17:13:45 +00:00
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
|
|
|
included do
|
|
|
|
before_create :cache_delete
|
2018-06-05 10:37:52 +00:00
|
|
|
after_commit :cache_delete
|
2017-01-31 17:13:45 +00:00
|
|
|
end
|
|
|
|
|
2018-04-12 14:57:37 +00:00
|
|
|
def cache_update(other)
|
2017-01-31 17:13:45 +00:00
|
|
|
cache_delete if respond_to?('cache_delete')
|
2018-04-12 14:57:37 +00:00
|
|
|
other.cache_delete if other.respond_to?('cache_delete')
|
2017-06-16 20:43:09 +00:00
|
|
|
true
|
2017-01-31 17:13:45 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def cache_delete
|
2019-09-18 12:24:40 +00:00
|
|
|
cache_keys = []
|
2017-01-31 17:13:45 +00:00
|
|
|
|
|
|
|
# delete by id with attributes_with_association_ids caches
|
2019-09-18 12:24:40 +00:00
|
|
|
cache_keys.push "#{self.class}::aws::#{id}"
|
2017-01-31 17:13:45 +00:00
|
|
|
|
2019-09-18 12:24:40 +00:00
|
|
|
# delete caches of lookup_keys (e.g. id, name, email, login, number)
|
|
|
|
self.class.lookup_keys.each do |lookup_key|
|
|
|
|
cache_keys.push "#{self.class}::#{self[lookup_key]}"
|
2017-01-31 17:13:45 +00:00
|
|
|
|
2019-09-18 12:24:40 +00:00
|
|
|
next if !saved_changes? || !saved_changes.key?(lookup_key)
|
|
|
|
|
|
|
|
obsolete_lookup_key = saved_changes[lookup_key][0]
|
|
|
|
cache_keys.push "#{self.class}::#{obsolete_lookup_key}"
|
2017-01-31 17:13:45 +00:00
|
|
|
end
|
|
|
|
|
2019-09-18 12:24:40 +00:00
|
|
|
cache_keys.each do |key|
|
2017-01-31 17:13:45 +00:00
|
|
|
Cache.delete(key)
|
2017-10-01 12:25:52 +00:00
|
|
|
end
|
2017-01-31 17:13:45 +00:00
|
|
|
|
2017-06-16 20:43:09 +00:00
|
|
|
true
|
2017-01-31 17:13:45 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
# methods defined here are going to extend the class, not the instance of it
|
|
|
|
class_methods do
|
|
|
|
|
|
|
|
def cache_set(data_id, data)
|
|
|
|
key = "#{self}::#{data_id}"
|
2021-01-05 11:35:56 +00:00
|
|
|
# cache for 4 hours max to lower impact of race conditions
|
|
|
|
Cache.write(key, data, expires_in: 4.hours)
|
2017-01-31 17:13:45 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def cache_get(data_id)
|
|
|
|
key = "#{self}::#{data_id}"
|
2021-05-31 13:05:54 +00:00
|
|
|
Cache.read(key)
|
2017-01-31 17:13:45 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|