summaryrefslogtreecommitdiff
path: root/lib/gitlab/changelog/template/context.rb
blob: 8a0796d767e2b14ff8d327c5a7ff1acc3a448eb5 (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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# frozen_string_literal: true

module Gitlab
  module Changelog
    module Template
      # Context is used to provide a binding/context to ERB templates used for
      # rendering changelogs.
      #
      # This class extends BasicObject so that we only expose the bare minimum
      # needed to render the ERB template.
      class Context < BasicObject
        MAX_NESTED_LOOPS = 4

        def initialize(variables)
          @variables = variables
          @loop_nesting = 0
        end

        def get_binding
          ::Kernel.binding
        end

        def each(value, &block)
          max = MAX_NESTED_LOOPS

          if @loop_nesting == max
            ::Kernel.raise(
              ::Template::TemplateError.new("You can only nest up to #{max} loops")
            )
          end

          @loop_nesting += 1
          result = value.each(&block) if value.respond_to?(:each)
          @loop_nesting -= 1

          result
        end

        # rubocop: disable Style/TrivialAccessors
        def variables
          @variables
        end
        # rubocop: enable Style/TrivialAccessors

        def read(source, *steps)
          current = source

          steps.each do |step|
            case current
            when ::Hash
              current = current[step]
            when ::Array
              return '' unless step.is_a?(::Integer)

              current = current[step]
            else
              break
            end
          end

          current
        end

        def truthy?(value)
          value.respond_to?(:any?) ? value.any? : !!value
        end
      end
    end
  end
end