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_file/blob.rb

66 lines
1.5 KiB
Ruby
Raw Normal View History

require "active_file/site"
2017-07-03 14:13:50 -04:00
require "active_file/filename"
2017-07-01 08:24:00 -04:00
# Schema: id, key, filename, content_type, metadata, byte_size, checksum, created_at
2017-06-30 13:12:58 -04:00
class ActiveFile::Blob < ActiveRecord::Base
self.table_name = "rails_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 :site
2017-06-30 13:12:58 -04:00
class << self
def build_after_upload(data:, filename:, content_type: nil, metadata: nil)
new.tap do |blob|
blob.filename = name
2017-07-01 06:47:13 -04:00
blob.content_type = content_type # Marcel::MimeType.for(data, name: name, declared_type: content_type)
blob.upload data
2017-06-30 13:12:58 -04:00
end
end
def create_after_upload!(data:, filename:, content_type: nil, metadata: nil)
build_after_upload(data: data, filename: filename, content_type: content_type, metadata: metadata).tap(&:save!)
end
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
2017-07-03 14:13:50 -04:00
ActiveFile::Filename.new(self[:filename])
end
2017-07-03 14:14:28 -04:00
def url(disposition: :inline, expires_in: 5.minutes)
site.url key, disposition: disposition, expires_in: expires_in
2017-06-30 13:12:58 -04:00
end
2017-06-30 18:13:23 -04:00
2017-07-01 06:47:13 -04:00
def upload(data)
site.upload(key, data)
self.checksum = site.checksum(key)
self.byte_size = site.byte_size(key)
2017-07-01 06:47:13 -04:00
end
def download
site.download key
end
2017-06-30 13:12:58 -04:00
def delete
2017-07-01 06:47:13 -04:00
site.delete key
2017-06-30 13:12:58 -04:00
end
def purge
delete
destroy
end
def purge_later
ActiveFile::PurgeJob.perform_later(self)
end
end