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

68 lines
1.5 KiB
Ruby
Raw Normal View History

require "active_vault/site"
require "active_vault/filename"
2017-07-01 08:24:00 -04:00
# Schema: id, key, filename, content_type, metadata, byte_size, checksum, created_at
class ActiveVault::Blob < ActiveRecord::Base
self.table_name = "active_vault_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(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
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
ActiveVault::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)
site.url key, expires_in: expires_in, disposition: disposition, filename: filename
2017-06-30 13:12:58 -04:00
end
2017-06-30 18:13:23 -04:00
def upload(io)
site.upload(key, io)
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
ActiveVault::PurgeJob.perform_later(self)
2017-06-30 13:12:58 -04:00
end
end