Class: Para::Cloneable::AttachmentsCloner

Inherits:
Object
  • Object
show all
Defined in:
lib/para/cloneable/attachments_cloner.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(original, clone) ⇒ AttachmentsCloner

Returns a new instance of AttachmentsCloner.



6
7
8
9
# File 'lib/para/cloneable/attachments_cloner.rb', line 6

def initialize(original, clone)
  @original = original
  @clone = clone
end

Instance Attribute Details

#cloneObject (readonly)

Returns the value of attribute clone.



4
5
6
# File 'lib/para/cloneable/attachments_cloner.rb', line 4

def clone
  @clone
end

#originalObject (readonly)

Returns the value of attribute original.



4
5
6
# File 'lib/para/cloneable/attachments_cloner.rb', line 4

def original
  @original
end

Instance Method Details

#clone!Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/para/cloneable/attachments_cloner.rb', line 11

def clone!
  return unless defined?(ActiveStorage)
  
  attachment_reflections = original.class.reflections.select { |k, v| 
    k.to_s.match(/_attachment\z/) && 
    v.options[:class_name] == "ActiveStorage::Attachment" 
  }

  attachment_reflections.each do |name, reflection|
    original_attachment = original.send(name)
    next unless original_attachment
    
    association_name = name.gsub(/_attachment\z/, "")

    Para::ActiveStorageDownloader.new(original_attachment).download_blob_to_tempfile do |tempfile|
      clone.send(association_name).attach({
        io: tempfile,
        filename: original_attachment.blob.filename,
        content_type: original_attachment.blob.content_type
      })
    end
  end
end