/
create_many.rb
56 lines (44 loc) · 1.5 KB
/
create_many.rb
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
# frozen_string_literal: true
module ActiveStorage
class Attached::Changes::CreateMany # :nodoc:
attr_reader :name, :record, :attachables, :pending_uploads
def initialize(name, record, attachables, pending_uploads: [])
@name, @record, @attachables = name, record, Array(attachables)
blobs.each(&:identify_without_saving)
@pending_uploads = Array(pending_uploads) + subchanges_without_blobs
attachments
end
def attachments
@attachments ||= subchanges.collect(&:attachment)
end
def blobs
@blobs ||= subchanges.collect(&:blob)
end
def upload
pending_uploads.each(&:upload)
end
def save
assign_associated_attachments
reset_associated_blobs
end
private
def subchanges
@subchanges ||= attachables.collect { |attachable| build_subchange_from(attachable) }
end
def build_subchange_from(attachable)
ActiveStorage::Attached::Changes::CreateOneOfMany.new(name, record, attachable)
end
def subchanges_without_blobs
subchanges.reject { |subchange| subchange.attachable.is_a?(ActiveStorage::Blob) }
end
def assign_associated_attachments
record.public_send("#{name}_attachments=", persisted_or_new_attachments)
end
def reset_associated_blobs
record.public_send("#{name}_blobs").reset
end
def persisted_or_new_attachments
attachments.select { |attachment| attachment.persisted? || attachment.new_record? }
end
end
end