Class: Katalyst::Content::DuplicatesAttachments::DupMany

Inherits:
Object
  • Object
show all
Defined in:
app/models/concerns/katalyst/content/duplicates_attachments.rb

Overview

Duplicates has_many_attached attachments from source to target. Public API: can be used directly for models that want to duplicate a specific attachment without including the concern, e.g. DuplicatesAttachments::DupMany.new(:slides).apply(source, self)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ DupMany

Returns a new instance of DupMany.



55
56
57
# File 'app/models/concerns/katalyst/content/duplicates_attachments.rb', line 55

def initialize(name)
  @name = name.to_s
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



53
54
55
# File 'app/models/concerns/katalyst/content/duplicates_attachments.rb', line 53

def name
  @name
end

Instance Method Details

#apply(source, target) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'app/models/concerns/katalyst/content/duplicates_attachments.rb', line 59

def apply(source, target)
  current = source.public_send(name)
  change  = source.attachment_changes[name]

  # if attachments have changed, duplicate the change, otherwise attach the existing blobs
  if change.is_a?(ActiveStorage::Attached::Changes::CreateMany)
    target.public_send("#{name}=", change.attachables)
  elsif change.is_a?(ActiveStorage::Attached::Changes::DeleteMany)
    # no-op, drop the attachments, if any
  elsif current.attached?
    blobs = current.attachments.reject(&:marked_for_destruction?).map(&:blob)
    target.public_send("#{name}=", blobs) if blobs.any?
  end
end