aboutsummaryrefslogtreecommitdiffstats
path: root/activestorage
diff options
context:
space:
mode:
authorGeorge Claghorn <george.claghorn@gmail.com>2018-08-09 19:53:12 -0400
committerGeorge Claghorn <george.claghorn@gmail.com>2018-08-09 19:53:12 -0400
commit10129fbf57ef851ad56158529081afa05ea1c030 (patch)
tree0dd0418e147916bb6631c0f3578bdc7584e47b22 /activestorage
parent482b74e793301bda3e6c8282a064485a6db01c55 (diff)
downloadrails-10129fbf57ef851ad56158529081afa05ea1c030.tar.gz
rails-10129fbf57ef851ad56158529081afa05ea1c030.tar.bz2
rails-10129fbf57ef851ad56158529081afa05ea1c030.zip
DRY up web image checks in ActiveStorage::Variant
Diffstat (limited to 'activestorage')
-rw-r--r--activestorage/app/models/active_storage/variant.rb42
1 files changed, 24 insertions, 18 deletions
diff --git a/activestorage/app/models/active_storage/variant.rb b/activestorage/app/models/active_storage/variant.rb
index 056fd2be99..239df34d81 100644
--- a/activestorage/app/models/active_storage/variant.rb
+++ b/activestorage/app/models/active_storage/variant.rb
@@ -1,5 +1,7 @@
# frozen_string_literal: true
+require "ostruct"
+
# Image blobs can have variants that are the result of a set of transformations applied to the original.
# These variants are used to create thumbnails, fixed-size avatars, or any other derivative image from the
# original.
@@ -51,7 +53,7 @@
# * {ImageProcessing::Vips}[https://github.com/janko-m/image_processing/blob/master/doc/vips.md#methods]
# * {ruby-vips reference}[http://www.rubydoc.info/gems/ruby-vips/Vips/Image]
class ActiveStorage::Variant
- WEB_IMAGE_CONTENT_TYPES = %w( image/png image/jpeg image/jpg image/gif )
+ WEB_IMAGE_CONTENT_TYPES = %w[ image/png image/jpeg image/jpg image/gif ]
attr_reader :blob, :variation
delegate :service, to: :blob
@@ -95,27 +97,11 @@ class ActiveStorage::Variant
def process
blob.open do |image|
- transform image do |output|
- upload output
- end
+ transform(image) { |output| upload(output) }
end
end
-
- def filename
- if WEB_IMAGE_CONTENT_TYPES.include?(blob.content_type)
- blob.filename
- else
- ActiveStorage::Filename.new("#{blob.filename.base}.png")
- end
- end
-
- def content_type
- blob.content_type.presence_in(WEB_IMAGE_CONTENT_TYPES) || "image/png"
- end
-
def transform(image)
- format = "png" unless WEB_IMAGE_CONTENT_TYPES.include?(blob.content_type)
result = variation.transform(image, format: format)
begin
@@ -128,4 +114,24 @@ class ActiveStorage::Variant
def upload(file)
service.upload(key, file)
end
+
+
+ def specification
+ @specification ||=
+ if WEB_IMAGE_CONTENT_TYPES.include?(blob.content_type)
+ Specification.new \
+ filename: blob.filename,
+ content_type: blob.content_type,
+ format: nil
+ else
+ Specification.new \
+ filename: ActiveStorage::Filename.new("#{blob.filename.base}.png"),
+ content_type: "image/png",
+ format: "png"
+ end
+ end
+
+ delegate :filename, :content_type, :format, to: :specification
+
+ class Specification < OpenStruct; end
end