summaryrefslogtreecommitdiff
path: root/lib/gitlab/with_feature_category.rb
blob: 65d21daf78aaa802c328b4768b708de74de79efc (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
# frozen_string_literal: true

module Gitlab
  module WithFeatureCategory
    extend ActiveSupport::Concern
    include Gitlab::ClassAttributes

    class_methods do
      def feature_category(category, actions = [])
        feature_category_configuration[category] ||= []
        feature_category_configuration[category] += actions.map(&:to_s)

        validate_config!(feature_category_configuration)
      end

      def feature_category_for_action(action)
        category_config = feature_category_configuration.find do |_, actions|
          actions.empty? || actions.include?(action)
        end

        category_config&.first || superclass_feature_category_for_action(action)
      end

      private

      def validate_config!(config)
        empty = config.find { |_, actions| actions.empty? }
        duplicate_actions = config.values.map(&:uniq).flatten.group_by(&:itself).select { |_, v| v.count > 1 }.keys

        if config.length > 1 && empty
          raise ArgumentError, "#{empty.first} is defined for all actions, but other categories are set"
        end

        if duplicate_actions.any?
          raise ArgumentError, "Actions have multiple feature categories: #{duplicate_actions.join(', ')}"
        end
      end

      def feature_category_configuration
        class_attributes[:feature_category_config] ||= {}
      end

      def superclass_feature_category_for_action(action)
        return unless superclass.respond_to?(:feature_category_for_action)

        superclass.feature_category_for_action(action)
      end
    end
  end
end