aboutsummaryrefslogtreecommitdiffstats
path: root/lib/active_storage/blob.rb
diff options
context:
space:
mode:
authorDavid Heinemeier Hansson <david@loudthinking.com>2017-07-06 11:33:29 +0200
committerDavid Heinemeier Hansson <david@loudthinking.com>2017-07-06 11:33:29 +0200
commitc624df326a4ef36919a5195a3c5509fab97dcba3 (patch)
treea8e07aabde7548d5bd4a322a9898ad123cfa40f7 /lib/active_storage/blob.rb
parent5869045f2e71f0abdf3add19629d23a46b9fff0d (diff)
downloadrails-c624df326a4ef36919a5195a3c5509fab97dcba3.tar.gz
rails-c624df326a4ef36919a5195a3c5509fab97dcba3.tar.bz2
rails-c624df326a4ef36919a5195a3c5509fab97dcba3.zip
ActiveVault -> ActiveStorage
Yaroslav agreed to hand over the gem name ❤️
Diffstat (limited to 'lib/active_storage/blob.rb')
-rw-r--r--lib/active_storage/blob.rb68
1 files changed, 68 insertions, 0 deletions
diff --git a/lib/active_storage/blob.rb b/lib/active_storage/blob.rb
new file mode 100644
index 0000000000..edf57b5c78
--- /dev/null
+++ b/lib/active_storage/blob.rb
@@ -0,0 +1,68 @@
+require "active_storage/site"
+require "active_storage/filename"
+require "active_storage/purge_job"
+
+# Schema: id, key, filename, content_type, metadata, byte_size, checksum, created_at
+class ActiveStorage::Blob < ActiveRecord::Base
+ self.table_name = "active_storage_blobs"
+
+ has_secure_token :key
+ store :metadata, coder: JSON
+
+ class_attribute :site
+
+ class << self
+ def build_after_upload(io:, filename:, content_type: nil, metadata: nil)
+ new.tap do |blob|
+ blob.filename = filename
+ blob.content_type = content_type
+ blob.metadata = metadata
+
+ blob.upload io
+ 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!)
+ end
+ end
+
+ # 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
+
+ def filename
+ ActiveStorage::Filename.new(self[:filename])
+ end
+
+ def url(expires_in: 5.minutes, disposition: :inline)
+ site.url key, expires_in: expires_in, disposition: disposition, filename: filename
+ end
+
+
+ def upload(io)
+ site.upload(key, io)
+
+ self.checksum = site.checksum(key)
+ self.byte_size = site.byte_size(key)
+ end
+
+ def download
+ site.download key
+ end
+
+
+ def delete
+ site.delete key
+ end
+
+ def purge
+ delete
+ destroy
+ end
+
+ def purge_later
+ ActiveStorage::PurgeJob.perform_later(self)
+ end
+end