1# frozen_string_literal: true
2
3require 'active_support/inflector'
4
5module InjectEnterpriseEditionModule
6  def prepend_mod_with(constant_name, namespace: Object, with_descendants: false)
7    each_extension_for(constant_name, namespace) do |constant|
8      prepend_module(constant, with_descendants)
9    end
10  end
11
12  def extend_mod_with(constant_name, namespace: Object)
13    each_extension_for(
14      constant_name,
15      namespace,
16      &method(:extend))
17  end
18
19  def include_mod_with(constant_name, namespace: Object)
20    each_extension_for(
21      constant_name,
22      namespace,
23      &method(:include))
24  end
25
26  def prepend_mod(with_descendants: false)
27    prepend_mod_with(name, with_descendants: with_descendants) # rubocop: disable Cop/InjectEnterpriseEditionModule
28  end
29
30  def extend_mod
31    extend_mod_with(name) # rubocop: disable Cop/InjectEnterpriseEditionModule
32  end
33
34  def include_mod
35    include_mod_with(name) # rubocop: disable Cop/InjectEnterpriseEditionModule
36  end
37
38  private
39
40  def prepend_module(mod, with_descendants)
41    prepend(mod)
42
43    if with_descendants
44      descendants.each { |descendant| descendant.prepend(mod) }
45    end
46  end
47
48  def each_extension_for(constant_name, namespace)
49    Gitlab.extensions.each do |extension_name|
50      extension_namespace =
51        const_get_maybe_false(namespace, extension_name.upcase)
52
53      extension_module =
54        const_get_maybe_false(extension_namespace, constant_name)
55
56      yield(extension_module) if extension_module
57    end
58  end
59
60  def const_get_maybe_false(mod, name)
61    mod && mod.const_defined?(name, false) && mod.const_get(name, false)
62  end
63end
64
65Module.prepend(InjectEnterpriseEditionModule)
66