summaryrefslogtreecommitdiff
path: root/app/models/concerns
diff options
context:
space:
mode:
authorMatija Čupić <matteeyah@gmail.com>2018-02-05 17:07:49 +0100
committerMatija Čupić <matteeyah@gmail.com>2018-02-05 17:07:49 +0100
commitaa60c7a2b521d8a30f10fcb31beb0cdd39c5cbbc (patch)
tree0e3c47cdc7a1ce9c829b3154421c34055bf4b120 /app/models/concerns
parentc92e1d731c8e76bcba3532cf51edc3d53abc1e1f (diff)
downloadgitlab-ce-aa60c7a2b521d8a30f10fcb31beb0cdd39c5cbbc.tar.gz
Extract attribute caching to RedisCacheable concern
Diffstat (limited to 'app/models/concerns')
-rw-r--r--app/models/concerns/redis_cacheable.rb41
1 files changed, 41 insertions, 0 deletions
diff --git a/app/models/concerns/redis_cacheable.rb b/app/models/concerns/redis_cacheable.rb
new file mode 100644
index 00000000000..249ebf9af07
--- /dev/null
+++ b/app/models/concerns/redis_cacheable.rb
@@ -0,0 +1,41 @@
+module RedisCacheable
+ extend ActiveSupport::Concern
+ include Gitlab::Utils::StrongMemoize
+
+ CACHED_ATTRIBUTES_EXPIRY_TIME = 24.hours
+
+ class_methods do
+ def cached_attr_reader(*attributes)
+ attributes.each do |attribute|
+ define_method("#{attribute}") do
+ cached_attribute(attribute) || read_attribute(attribute)
+ end
+ end
+ end
+ end
+
+ def cached_attribute(attribute)
+ (cached_attributes || {})[attribute]
+ end
+
+ def cache_attributes(values)
+ Gitlab::Redis::SharedState.with do |redis|
+ redis.set(cache_attribute_key, values.to_json, ex: CACHED_ATTRIBUTES_EXPIRY_TIME)
+ end
+ end
+
+ private
+
+ def cache_attribute_key
+ "#{self.class.name}:attributes:#{self.id}"
+ end
+
+ def cached_attributes
+ strong_memoize(:cached_attributes) do
+ Gitlab::Redis::SharedState.with do |redis|
+ data = redis.get(cache_attribute_key)
+ JSON.parse(data, symbolize_names: true) if data
+ end
+ end
+ end
+end