2018-08-03 13:22:24 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2018-02-05 11:07:49 -05:00
|
|
|
module RedisCacheable
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
include Gitlab::Utils::StrongMemoize
|
|
|
|
|
|
|
|
CACHED_ATTRIBUTES_EXPIRY_TIME = 24.hours
|
|
|
|
|
|
|
|
class_methods do
|
|
|
|
def cached_attr_reader(*attributes)
|
2018-05-08 06:20:54 -04:00
|
|
|
attributes.each do |attribute|
|
2018-05-18 09:33:54 -04:00
|
|
|
define_method(attribute) do
|
2018-05-18 10:34:08 -04:00
|
|
|
unless self.has_attribute?(attribute)
|
|
|
|
raise ArgumentError, "`cached_attr_reader` requires the #{self.class.name}\##{attribute} attribute to have a database column"
|
|
|
|
end
|
|
|
|
|
2018-05-16 15:23:43 -04:00
|
|
|
cached_attribute(attribute) || read_attribute(attribute)
|
2018-05-08 06:20:54 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2018-02-05 11:07:49 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def cached_attribute(attribute)
|
2018-05-16 15:23:43 -04:00
|
|
|
cached_value = (cached_attributes || {})[attribute]
|
|
|
|
cast_value_from_cache(attribute, cached_value) if cached_value
|
2018-02-05 11:07:49 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def cache_attributes(values)
|
2020-04-22 08:09:29 -04:00
|
|
|
Gitlab::Redis::Cache.with do |redis|
|
2018-02-05 11:07:49 -05:00
|
|
|
redis.set(cache_attribute_key, values.to_json, ex: CACHED_ATTRIBUTES_EXPIRY_TIME)
|
|
|
|
end
|
2018-05-11 12:36:16 -04:00
|
|
|
|
|
|
|
clear_memoization(:cached_attributes)
|
2018-02-05 11:07:49 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def cache_attribute_key
|
2018-02-05 14:43:23 -05:00
|
|
|
"cache:#{self.class.name}:#{self.id}:attributes"
|
2018-02-05 11:07:49 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def cached_attributes
|
|
|
|
strong_memoize(:cached_attributes) do
|
2020-04-22 08:09:29 -04:00
|
|
|
Gitlab::Redis::Cache.with do |redis|
|
2018-02-05 11:07:49 -05:00
|
|
|
data = redis.get(cache_attribute_key)
|
2020-04-30 14:09:38 -04:00
|
|
|
Gitlab::Json.parse(data, symbolize_names: true) if data
|
2018-02-05 11:07:49 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2018-05-15 15:55:16 -04:00
|
|
|
|
|
|
|
def cast_value_from_cache(attribute, value)
|
2018-12-15 04:06:56 -05:00
|
|
|
self.class.type_for_attribute(attribute.to_s).cast(value)
|
2018-05-15 15:55:16 -04:00
|
|
|
end
|
2018-02-05 11:07:49 -05:00
|
|
|
end
|