Class: EchoUploads::File

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
lib/echo_uploads/file.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.default_key_procObject

Returns a proc that takes as its only argument an ActionDispatch::UploadedFile and returns a key string.



19
20
21
22
23
24
25
26
27
28
# File 'lib/echo_uploads/file.rb', line 19

def self.default_key_proc
  ->(file) do
    digest = Digest::SHA512.new
    file.rewind
    until file.eof?
      digest.update file.read(1000)
    end
    digest.hexdigest
  end
end

.prune_temporary!Object



66
67
68
69
70
# File 'lib/echo_uploads/file.rb', line 66

def self.prune_temporary!
  where(temporary: true).where(['expires_at < ?', Time.now]).each do |file_meta|
    file_meta.destroy
  end
end

Instance Method Details

#compute_mime!Object



12
13
14
15
# File 'lib/echo_uploads/file.rb', line 12

def compute_mime!
  type = MIME::Types.type_for(original_filename).first
  self.mime_type = type ? type.content_type : 'application/octet-stream'
end

#delete_file_conditionallyObject

Deletes the file on disk if and only if no other instances of EchoUpload::File reference it.



32
33
34
35
36
# File 'lib/echo_uploads/file.rb', line 32

def delete_file_conditionally
  unless self.class.where(key: key).where(['id != ?', id]).exists?
    storage.delete key
  end
end

#original_filenameObject



38
39
40
# File 'lib/echo_uploads/file.rb', line 38

def original_filename
  original_basename + original_extension
end

#persist!(attr, file, options) ⇒ Object

Pass in an attribute name, an ActionDispatch::UploadedFile, and an options hash.



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/echo_uploads/file.rb', line 43

def persist!(attr, file, options)
  # Configure and save the metadata object.
  self.key = options[:key].call file
  self.owner_attr = attr
  self.original_extension = ::File.extname(file.original_filename)
  self.original_basename = ::File.basename(file.original_filename, original_extension)
  compute_mime!
  self.storage_type = options[:storage].name
  save!

  # Write the file to the filestore.
  storage.write key, file

  # Prune any expired temporary files. (Unless automatic pruning was turned off in
  # the app config.)
  unless (
    Rails.configuration.echo_uploads.respond_to?(:prune_tmp_files_on_upload) and
    !Rails.configuration.echo_uploads.prune_tmp_files_on_upload
  )
    self.class.prune_temporary!
  end
end

#storageObject



72
73
74
# File 'lib/echo_uploads/file.rb', line 72

def storage
  Object.const_get(storage_type).new
end