Welcome to mirror list, hosted at ThFree Co, Russian Federation.

update_namespace_statistics.rb « concerns « models « app - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 26d6fc102282a4017a1b04f26532ea534572ac50 (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
# frozen_string_literal: true

# This module provides helpers for updating `NamespaceStatistics` with `after_save` and
# `after_destroy` hooks.
#
# Models including this module must respond to and return a `namespace`
#
# Example:
#
# class DependencyProxy::Manifest
#   include UpdateNamespaceStatistics
#
#   belongs_to :group
#   alias_attribute :namespace, :group
#
#   update_namespace_statistics namespace_statistics_name: :dependency_proxy_size
# end
module UpdateNamespaceStatistics
  extend ActiveSupport::Concern
  include AfterCommitQueue

  class_methods do
    attr_reader :namespace_statistics_name, :statistic_attribute

    # Configure the model to update `namespace_statistics_name` on NamespaceStatistics,
    # when `statistic_attribute` changes
    #
    # - namespace_statistics_name: A column of `NamespaceStatistics` to update
    # - statistic_attribute: An attribute of the current model, default to `size`
    def update_namespace_statistics(namespace_statistics_name:, statistic_attribute: :size)
      @namespace_statistics_name = namespace_statistics_name
      @statistic_attribute = statistic_attribute

      after_save(:schedule_namespace_statistics_refresh, if: :update_namespace_statistics?)
      after_destroy(:schedule_namespace_statistics_refresh)
    end

    private :update_namespace_statistics
  end

  included do
    private

    def update_namespace_statistics?
      saved_change_to_attribute?(self.class.statistic_attribute)
    end

    def schedule_namespace_statistics_refresh
      run_after_commit do
        Groups::UpdateStatisticsWorker.perform_async(namespace.id, [self.class.namespace_statistics_name])
      end
    end
  end
end