Skip to content

Commit 501552c

Browse files
committed
Preprocess thumbnails after upload
Only works in Rails 7.1
1 parent 6844e58 commit 501552c

File tree

2 files changed

+26
-8
lines changed

2 files changed

+26
-8
lines changed

app/models/alchemy/picture.rb

+5-1
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,11 @@ def self.preprocessor_class=(klass)
9797
end
9898

9999
# Use ActiveStorage image processing
100-
has_one_attached :image_file, service: :alchemy_cms
100+
has_one_attached :image_file, service: :alchemy_cms do |attachable|
101+
# Only works in Rails 7.1
102+
preprocessor_class.new(attachable).call
103+
Preprocessor.generate_thumbs!(attachable)
104+
end
101105

102106
validates_presence_of :image_file
103107
validate :image_file_type_allowed, :image_file_not_too_big,

app/models/alchemy/picture/preprocessor.rb

+21-7
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
module Alchemy
44
class Picture < BaseRecord
55
class Preprocessor
6-
def initialize(image_file)
7-
@image_file = image_file
6+
def initialize(attachable)
7+
@attachable = attachable
88
end
99

1010
# Preprocess images after upload
@@ -15,14 +15,28 @@ def initialize(image_file)
1515
#
1616
def call
1717
max_image_size = Alchemy::Config.get(:preprocess_image_resize)
18-
image_file.thumb!(max_image_size) if max_image_size.present?
19-
# Auto orient the image so EXIF orientation data is taken into account
20-
image_file.auto_orient!
18+
if max_image_size.present?
19+
self.class.process_thumb(attachable, size: max_image_size)
20+
end
2121
end
2222

23-
private
23+
attr_reader :attachable
2424

25-
attr_reader :image_file
25+
class << self
26+
def generate_thumbs!(attachable)
27+
Alchemy::Picture::THUMBNAIL_SIZES.values.each do |size|
28+
process_thumb(attachable, size: size, flatten: true)
29+
end
30+
end
31+
32+
private
33+
34+
def process_thumb(attachable, options = {})
35+
attachable.variant :thumb,
36+
**Alchemy::DragonflyToImageProcessing.call(options),
37+
preprocessed: true
38+
end
39+
end
2640
end
2741
end
2842
end

0 commit comments

Comments
 (0)