debian-mirror-gitlab/lib/gitlab/cache/request_cache.rb

64 lines
1.8 KiB
Ruby
Raw Normal View History

2018-12-13 13:39:08 +05:30
# frozen_string_literal: true
2017-09-10 17:25:29 +05:30
module Gitlab
module Cache
2018-11-08 19:23:39 +05:30
# See https://docs.gitlab.com/ee/development/utilities.html#requestcache
2017-09-10 17:25:29 +05:30
module RequestCache
def self.extended(klass)
return if klass < self
extension = Module.new
klass.const_set(:RequestCacheExtension, extension)
klass.prepend(extension)
end
2018-03-17 18:26:18 +05:30
attr_accessor :request_cache_key_block
2017-09-10 17:25:29 +05:30
def request_cache_key(&block)
if block_given?
2018-03-17 18:26:18 +05:30
self.request_cache_key_block = block
2017-09-10 17:25:29 +05:30
else
2018-03-17 18:26:18 +05:30
request_cache_key_block
2017-09-10 17:25:29 +05:30
end
end
def request_cache(method_name, &method_key_block)
2019-12-21 20:55:43 +05:30
const_get(:RequestCacheExtension, false).module_eval do
2017-09-10 17:25:29 +05:30
cache_key_method_name = "#{method_name}_cache_key"
define_method(method_name) do |*args|
store =
2018-12-05 23:21:45 +05:30
if Gitlab::SafeRequestStore.active?
Gitlab::SafeRequestStore.store
2017-09-10 17:25:29 +05:30
else
ivar_name = # ! and ? cannot be used as ivar name
"@cache_#{method_name.to_s.tr('!?', "\u2605\u2606")}"
instance_variable_get(ivar_name) ||
instance_variable_set(ivar_name, {})
end
2018-03-17 18:26:18 +05:30
key = __send__(cache_key_method_name, args) # rubocop:disable GitlabSecurity/PublicSend
2017-09-10 17:25:29 +05:30
store.fetch(key) { store[key] = super(*args) }
end
define_method(cache_key_method_name) do |args|
klass = self.class
instance_key = instance_exec(&klass.request_cache_key) if
klass.request_cache_key
method_key = instance_exec(&method_key_block) if method_key_block
[klass.name, method_name, *instance_key, *method_key, *args]
.join(':')
end
private cache_key_method_name
end
end
end
end
end