summaryrefslogtreecommitdiff
path: root/lib/gitlab/cache/request_store_wrap.rb
blob: 3e0a5f06b53788a0723c314e7f082cbde5d18c06 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
module Gitlab
  module Cache
    # This module provides a simple way to cache values in RequestStore,
    # and the cache key would be based on the class name, method name,
    # customized instance level values, and arguments.
    #
    # A simple example:
    #
    # class UserAccess
    #   extend Gitlab::Cache::RequestStoreWrap
    #
    #   request_store_wrap_key do
    #     [user.id, project.id]
    #   end
    #
    #   request_store_wrap def can_push_to_branch?(ref)
    #     # ...
    #   end
    # end
    #
    # This way, the result of `can_push_to_branch?` would be cached in
    # `RequestStore.store` based on the cache key.
    module RequestStoreWrap
      def self.extended(klass)
        return if klass < self

        extension = Module.new
        klass.const_set(:RequestStoreWrapExtension, extension)
        klass.prepend(extension)
      end

      def request_store_wrap_key(&block)
        if block_given?
          @request_store_wrap_key = block
        else
          @request_store_wrap_key
        end
      end

      def request_store_wrap(method_name)
        const_get(:RequestStoreWrapExtension)
          .send(:define_method, method_name) do |*args|
            return super(*args) unless RequestStore.active?

            klass = self.class
            key = [klass.name,
                   method_name,
                   *instance_exec(&klass.request_store_wrap_key),
                   *args].join(':')

            if RequestStore.store.key?(key)
              RequestStore.store[key]
            else
              RequestStore.store[key] = super(*args)
            end
          end
      end
    end
  end
end