Skip to content

Commit

Permalink
Preprocess thumbnails after upload
Browse files Browse the repository at this point in the history
Only works in Rails 7.1
  • Loading branch information
tvdeyen committed Aug 4, 2024
1 parent 09c3d21 commit 06c3c7d
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
6 changes: 5 additions & 1 deletion app/models/alchemy/picture.rb
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,11 @@ def self.preprocessor_class=(klass)
end

# Use ActiveStorage image processing
has_one_attached :image_file, service: :alchemy_cms
has_one_attached :image_file, service: :alchemy_cms do |attachable|
# Only works in Rails 7.1
preprocessor_class.new(attachable).call
Preprocessor.generate_thumbs!(attachable)
end

validates_presence_of :image_file
validate :image_file_type_allowed, :image_file_not_too_big,
Expand Down
28 changes: 21 additions & 7 deletions app/models/alchemy/picture/preprocessor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
module Alchemy
class Picture < BaseRecord
class Preprocessor
def initialize(image_file)
@image_file = image_file
def initialize(attachable)
@attachable = attachable
end

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

private
attr_reader :attachable

attr_reader :image_file
class << self
def generate_thumbs!(attachable)
Alchemy::Picture::THUMBNAIL_SIZES.values.each do |size|
process_thumb(attachable, size: size, flatten: true)
end
end

private

def process_thumb(attachable, options = {})
attachable.variant :thumb,
**Alchemy::DragonflyToImageProcessing.call(options),
preprocessed: true
end
end
end
end
end

0 comments on commit 06c3c7d

Please sign in to comment.