Class: Katalyst::Content::DuplicatesAttachments::DupOne

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

Overview

Duplicates a has_one_attached attachment 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::DupOne.new(:image).apply(source, self)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ DupOne

Returns a new instance of DupOne.



28
29
30
# File 'app/models/concerns/katalyst/content/duplicates_attachments.rb', line 28

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

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



26
27
28
# File 'app/models/concerns/katalyst/content/duplicates_attachments.rb', line 26

def name
  @name
end

Instance Method Details

#apply(source, target) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'app/models/concerns/katalyst/content/duplicates_attachments.rb', line 32

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

  # if attachment has changed, duplicate the change, otherwise attach the existing blob
  if change.is_a?(ActiveStorage::Attached::Changes::CreateOne)
    target.public_send("#{name}=", change.attachable)
  elsif change.is_a?(ActiveStorage::Attached::Changes::DeleteOne) ||
      current.attachment&.marked_for_destruction?
    # no-op, drop the attachment, if any
  elsif current.attached?
    target.public_send("#{name}=", current.blob)
  end
end