1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00
rails--rails/lib/active_storage/blob.rb

89 lines
2.2 KiB
Ruby
Raw Normal View History

require "active_storage/service"
require "active_storage/filename"
require "active_storage/purge_job"
2017-07-01 08:24:00 -04:00
# Schema: id, key, filename, content_type, metadata, byte_size, checksum, created_at
class ActiveStorage::Blob < ActiveRecord::Base
self.table_name = "active_storage_blobs"
2017-06-30 13:12:58 -04:00
has_secure_token :key
2017-06-30 13:12:58 -04:00
store :metadata, coder: JSON
class_attribute :service
2017-06-30 13:12:58 -04:00
class << self
def build_after_upload(io:, filename:, content_type: nil, metadata: nil)
2017-06-30 13:12:58 -04:00
new.tap do |blob|
2017-07-04 12:43:56 -04:00
blob.filename = filename
2017-07-04 12:44:06 -04:00
blob.content_type = content_type
2017-07-05 09:18:42 -04:00
blob.metadata = metadata
2017-07-04 12:44:06 -04:00
blob.upload io
2017-06-30 13:12:58 -04:00
end
end
def create_after_upload!(io:, filename:, content_type: nil, metadata: nil)
build_after_upload(io: io, filename: filename, content_type: content_type, metadata: metadata).tap(&:save!)
2017-06-30 13:12:58 -04:00
end
2017-07-09 12:03:13 -04:00
def create_before_direct_upload!(filename:, byte_size:, checksum:, content_type: nil, metadata: nil)
create! filename: filename, byte_size: byte_size, checksum: checksum, content_type: content_type, metadata: metadata
end
2017-06-30 13:12:58 -04:00
end
2017-07-01 06:47:13 -04:00
# We can't wait until the record is first saved to have a key for it
def key
self[:key] ||= self.class.generate_unique_secure_token
end
2017-06-30 18:13:23 -04:00
2017-06-30 13:12:58 -04:00
def filename
ActiveStorage::Filename.new(self[:filename])
2017-07-03 14:13:50 -04:00
end
2017-07-03 14:14:28 -04:00
def url(expires_in: 5.minutes, disposition: :inline)
service.url key, expires_in: expires_in, disposition: disposition, filename: filename
2017-06-30 13:12:58 -04:00
end
2017-07-09 12:03:13 -04:00
def url_for_direct_upload(expires_in: 5.minutes)
service.url_for_direct_upload key, expires_in: expires_in, content_type: content_type, content_length: byte_size
end
2017-06-30 18:13:23 -04:00
def upload(io)
self.checksum = compute_checksum_in_chunks(io)
self.byte_size = io.size
2017-07-06 10:01:11 -04:00
service.upload(key, io, checksum: checksum)
2017-07-01 06:47:13 -04:00
end
2017-07-10 16:17:48 -04:00
def download(&block)
service.download key, &block
2017-07-01 06:47:13 -04:00
end
2017-06-30 13:12:58 -04:00
def delete
service.delete key
2017-06-30 13:12:58 -04:00
end
def purge
delete
destroy
end
def purge_later
ActiveStorage::PurgeJob.perform_later(self)
2017-06-30 13:12:58 -04:00
end
private
def compute_checksum_in_chunks(io)
Digest::MD5.new.tap do |checksum|
while chunk = io.read(5.megabytes)
checksum << chunk
end
io.rewind
end.base64digest
end
2017-06-30 13:12:58 -04:00
end