aboutsummaryrefslogtreecommitdiffstats
path: root/lib/active_vault/attachments.rb
blob: c66c1426505e445242e1e83cfb2ef034fbd292f4 (plain) (blame)
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
require "active_vault/attachment"
require "action_dispatch/http/upload"

module ActiveVault::Attachments
  def has_file(name)
    define_method(name) do
      (@active_vault_attachments ||= {})[name] ||=
        ActiveVault::Attachment.find_by(record_gid: to_gid.to_s, name: name)&.tap { |a| a.record = self }
    end

    define_method(:"#{name}=") do |attachable|
      case attachable
      when ActiveVault::Blob
        blob = attachable
      when ActionDispatch::Http::UploadedFile
        blob = ActiveVault::Blob.create_after_upload! \
          io: attachable.open,
          filename: attachable.original_filename,
          content_type: attachable.content_type
      when Hash
        blob = ActiveVault::Blob.create_after_upload!(attachable)
      when NilClass
        blob = nil
      end

      (@active_vault_attachments ||= {})[name] = blob ?
        ActiveVault::Attachment.create!(record_gid: to_gid.to_s, name: name, blob: blob)&.tap { |a| a.record = self } : nil
    end
  end
end