BigW Consortium Gitlab

configurable.rb 2.03 KB
Newer Older
1 2 3 4
module Gitlab
  module Ci
    class Config
      module Node
5 6 7 8 9 10 11 12 13 14 15
        ##
        # This mixin is responsible for adding DSL, which purpose is to
        # simplifly process of adding child nodes.
        #
        # This can be used only if parent node is a configuration entry that
        # holds a hash as a configuration value, for example:
        #
        # job:
        #   script: ...
        #   artifacts: ...
        #
16 17
        module Configurable
          extend ActiveSupport::Concern
18
          include Validatable
19

20 21
          included do
            validations do
22
              validates :config, type: Hash
23 24 25
            end
          end

26
          def compose!(deps = nil)
27
            return unless valid?
28

29 30 31 32
            self.class.nodes.each do |key, factory|
              factory
                .value(@config[key])
                .with(key: key, parent: self)
33

34 35
              @entries[key] = factory.create!
            end
36 37 38 39 40 41

            yield if block_given?

            @entries.each_value do |entry|
              entry.compose!(deps)
            end
42 43 44
          end

          class_methods do
45
            def nodes
46
              Hash[(@nodes || {}).map { |key, factory| [key, factory.dup] }]
47
            end
48

49
            private # rubocop:disable Lint/UselessAccessModifier
50

51 52
            def node(key, node, metadata)
              factory = Node::Factory.new(node)
53 54
                .with(description: metadata[:description])

55
              (@nodes ||= {}).merge!(key.to_sym => factory)
56
            end
57 58 59 60

            def helpers(*nodes)
              nodes.each do |symbol|
                define_method("#{symbol}_defined?") do
61
                  @entries[symbol].specified? if @entries[symbol]
62 63 64
                end

                define_method("#{symbol}_value") do
65 66 67
                  return unless @entries[symbol] && @entries[symbol].valid?

                  @entries[symbol].value
68 69 70 71 72
                end

                alias_method symbol.to_sym, "#{symbol}_value".to_sym
              end
            end
73 74 75 76 77 78
          end
        end
      end
    end
  end
end