aboutsummaryrefslogtreecommitdiffstats
path: root/activestorage/lib/active_storage/attached.rb
blob: 1b53818581df2c522f2369174b4130372f78bda1 (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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# frozen_string_literal: true

require "action_dispatch"
require "action_dispatch/http/upload"
require "active_support/core_ext/module/delegation"

module ActiveStorage
  # Abstract base class for the concrete ActiveStorage::Attached::One and ActiveStorage::Attached::Many
  # classes that both provide proxy access to the blob association for a record.
  class Attached
    attr_reader :name, :record, :dependent

    def initialize(name, record, dependent:)
      @name, @record, @dependent = name, record, dependent
    end

    private
      def change
        record.attachment_changes[name]
      end

      def create_blob_from(attachable)
        case attachable
        when ActiveStorage::Blob
          attachable
        when ActionDispatch::Http::UploadedFile, Rack::Test::UploadedFile
          ActiveStorage::Blob.create_after_upload! \
            io: attachable.open,
            filename: attachable.original_filename,
            content_type: attachable.content_type
        when Hash
          ActiveStorage::Blob.create_after_upload!(attachable)
        when String
          ActiveStorage::Blob.find_signed(attachable)
        else
          nil
        end
      end
  end
end

require "active_storage/attached/model"
require "active_storage/attached/one"
require "active_storage/attached/many"
require "active_storage/attached/changes"