Class: Dscf::Core::FileStorage::Uploader

Inherits:
Object
  • Object
show all
Defined in:
app/services/dscf/core/file_storage/uploader.rb

Overview

Handles file uploads with validation

Constant Summary collapse

DEFAULT_MAX_SIZE =
5.megabytes
DEFAULT_ALLOWED_TYPES =
%w[
  application/pdf
  image/png
  image/jpeg
  image/webp
].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Uploader

Returns a new instance of Uploader.



18
19
20
21
22
23
24
# File 'app/services/dscf/core/file_storage/uploader.rb', line 18

def initialize(options = {})
  @max_size = options[:max_size] || DEFAULT_MAX_SIZE
  @allowed_types = options[:allowed_types] || DEFAULT_ALLOWED_TYPES
  @record_class = options[:record_class]
  @client = options[:client] || Client.new(record_class: @record_class)
  @errors = []
end

Instance Attribute Details

#errorsObject (readonly)

Returns the value of attribute errors.



16
17
18
# File 'app/services/dscf/core/file_storage/uploader.rb', line 16

def errors
  @errors
end

Instance Method Details

#success?Boolean

Check if last upload was successful

Returns:

  • (Boolean)


64
65
66
# File 'app/services/dscf/core/file_storage/uploader.rb', line 64

def success?
  @errors.empty?
end

#upload(file, **options) ⇒ Hash?

Upload a single file

Parameters:

  • file (ActionDispatch::Http::UploadedFile, File, IO, Hash)
  • options (Hash)

    additional options (filename, metadata)

Returns:

  • (Hash, nil)

    hash with file_key, filename, content_type, size, metadata



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'app/services/dscf/core/file_storage/uploader.rb', line 30

def upload(file, **options)
  @errors = []

  return nil unless validate_file(file)

  result = @client.upload(file, filename: options[:filename])

  {
    file_key: result[:file_key],
    filename: result[:filename],
    content_type: result[:content_type],
    size: result[:size],
    metadata: options[:metadata] || {}
  }
rescue Client::UploadError => e
  @errors << e.message
  nil
rescue StandardError => e
  Rails.logger.error("FileStorage::Uploader error: #{e.message}")
  @errors << "An unexpected error occurred during upload"
  nil
end

#upload_many(files, **options) ⇒ Array<Hash>

Upload multiple files

Parameters:

  • files (Array<ActionDispatch::Http::UploadedFile>)
  • options (Hash)

    additional options

Returns:

  • (Array<Hash>)

    array of hashes with file info



57
58
59
60
61
# File 'app/services/dscf/core/file_storage/uploader.rb', line 57

def upload_many(files, **options)
  Array(files).filter_map do |file|
    upload(file, **options)
  end
end