summaryrefslogtreecommitdiff
path: root/lib/gitlab/ci/config/entry/simplifiable.rb
blob: 12764629686f141bafb3b7a39c0dcd2a363a4a24 (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
module Gitlab
  module Ci
    class Config
      module Entry
        class Simplifiable < SimpleDelegator
          EntryStrategy = Struct.new(:name, :condition)

          def initialize(config, **metadata)
            unless self.class.const_defined?(:UnknownStrategy)
              raise ArgumentError, 'UndefinedStrategy not available!'
            end

            strategy = self.class.strategies.find do |variant|
              variant.condition.call(config)
            end

            entry = self.class.entry_class(strategy)

            super(entry.new(config, metadata))
          end

          def self.strategy(name, **opts)
            EntryStrategy.new(name, opts.fetch(:if)).tap do |strategy|
              strategies.append(strategy)
            end
          end

          def self.strategies
            @strategies ||= []
          end

          def self.entry_class(strategy)
            if strategy.present?
              self.const_get(strategy.name)
            else
              self::UnknownStrategy
            end
          end
        end
      end
    end
  end
end