aboutsummaryrefslogtreecommitdiffstats
path: root/app/models/active_storage/variant.rb
diff options
context:
space:
mode:
Diffstat (limited to 'app/models/active_storage/variant.rb')
-rw-r--r--app/models/active_storage/variant.rb35
1 files changed, 35 insertions, 0 deletions
diff --git a/app/models/active_storage/variant.rb b/app/models/active_storage/variant.rb
new file mode 100644
index 0000000000..435033f980
--- /dev/null
+++ b/app/models/active_storage/variant.rb
@@ -0,0 +1,35 @@
+require "active_storage/blob"
+require "mini_magick"
+
+# Image blobs can have variants that are the result of a set of transformations applied to the original.
+class ActiveStorage::Variant
+ attr_reader :blob, :variation
+ delegate :service, to: :blob
+
+ def initialize(blob, variation)
+ @blob, @variation = blob, variation
+ end
+
+ def processed
+ process unless service.exist?(key)
+ self
+ end
+
+ def key
+ "variants/#{blob.key}/#{variation.key}"
+ end
+
+ def url(expires_in: 5.minutes, disposition: :inline)
+ service.url key, expires_in: expires_in, disposition: disposition, filename: blob.filename
+ end
+
+
+ private
+ def process
+ service.upload key, transform(service.download(blob.key))
+ end
+
+ def transform(io)
+ File.open MiniMagick::Image.read(io).tap { |image| variation.transform(image) }.path
+ end
+end