File: update_instance_variables_service.rb

package info (click to toggle)
gitlab 17.6.5-19
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 629,368 kB
  • sloc: ruby: 1,915,304; javascript: 557,307; sql: 60,639; xml: 6,509; sh: 4,567; makefile: 1,239; python: 406
file content (83 lines) | stat: -rw-r--r-- 2,150 bytes parent folder | download
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
71
72
73
74
75
76
77
78
79
80
81
82
83
# frozen_string_literal: true

# This class is a simplified version of assign_nested_attributes_for_collection_association from ActiveRecord
# https://github.com/rails/rails/blob/v6.0.2.1/activerecord/lib/active_record/nested_attributes.rb#L466

module Ci
  class UpdateInstanceVariablesService
    UNASSIGNABLE_KEYS = %w[id _destroy].freeze

    def initialize(params, current_user)
      @current_user = current_user
      @params = params[:variables_attributes]
    end

    def execute
      instantiate_records
      persist_records
    end

    def errors
      @records.to_a.flat_map { |r| r.errors.full_messages }
    end

    private

    attr_reader :params, :current_user

    def existing_records_by_id
      @existing_records_by_id ||= Ci::InstanceVariable
        .all
        .index_by { |var| var.id.to_s }
    end

    def instantiate_records
      @records = params.map do |attributes|
        find_or_initialize_record(attributes).tap do |record|
          record.assign_attributes(attributes.except(*UNASSIGNABLE_KEYS))
          record.mark_for_destruction if has_destroy_flag?(attributes)
        end
      end
    end

    def find_or_initialize_record(attributes)
      id = attributes[:id].to_s

      if id.blank?
        Ci::InstanceVariable.new
      else
        existing_records_by_id.fetch(id) { raise ActiveRecord::RecordNotFound }
      end
    end

    # overridden in EE
    def audit_change(instance_variable); end

    def persist_records
      changes = []
      success = false

      Ci::InstanceVariable.transaction do
        changes = @records.map do |record|
          if record.marked_for_destruction?
            { action: record.destroy, record: record }
          else
            { action: record.save, record: record }
          end
        end
        success = changes.all? { |change| change[:action] }

        raise ActiveRecord::Rollback unless success
      end

      changes.each { |change| audit_change change[:record] }

      success
    end

    def has_destroy_flag?(hash)
      Gitlab::Utils.to_boolean(hash['_destroy'])
    end
  end
end
Ci::UpdateInstanceVariablesService.prepend_mod