Welcome to mirror list, hosted at ThFree Co, Russian Federation.

update_instance_variables_service.rb « ci « services « app - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: ee513647d0812797ce47f3d660a1585f3586a3a3 (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
71
72
# 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)
      @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

    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

    def persist_records
      Ci::InstanceVariable.transaction do
        success = @records.map do |record|
          if record.marked_for_destruction?
            record.destroy
          else
            record.save
          end
        end.all?

        raise ActiveRecord::Rollback unless success

        success
      end
    end

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