Аккуратнее закрываем original + если не удалось оптимизировать, не оставляем файл временный

This commit is contained in:
Vasily Fedoseyev
2024-04-10 01:55:43 +03:00
parent d7cf90f139
commit 1fdb27c8ee
2 changed files with 11 additions and 8 deletions

View File

@@ -436,14 +436,14 @@ module Paperclip
end
def post_process_styles #:nodoc:
old_original = queued_for_write[:original]
styles.each do |name, args|
begin
raise RuntimeError.new("Style #{name} has no processors defined.") if args[:processors].blank?
queued_for_write[name] = args[:processors].inject(queued_for_write[:original]) do |file, processor|
Paperclip.processor(processor).make(file, args, self).tap do |new_file|
# closing intermediary tempfiles
file.close! if new_file != file && file.respond_to?(:close!) &&
(name == :original || !queued_for_write.value?(file))
file.close! if new_file != file && file.respond_to?(:close!) && !queued_for_write.value?(file)
end
end
rescue PaperclipError => e
@@ -451,6 +451,7 @@ module Paperclip
(errors[:processing] ||= []) << e.message if self.class.whiny
end
end
old_original.close! if old_original.respond_to?(:close!) && !queued_for_write.value?(old_original)
end
def interpolate pattern, style = default_style #:nodoc:

View File

@@ -3,10 +3,7 @@ require 'open3'
module Paperclip
class Optimizer < Processor
def make
optimized_file = optimize(@file)
return @file unless optimized_file && optimized_file.size > 0 # rubocop:disable Style/ZeroLengthPredicate
optimized_file
optimize(@file) || @file
end
def real_content_type
@@ -24,7 +21,7 @@ module Paperclip
when 'image/jpeg', 'image/jpg', 'image/pjpeg'
# NB: --stdout не работает, там бывают пустые файлы если оно решило ничего не делать
# нельзя `cp`, надо чтобы открытый файл указывал куда надо, поэтому `cat>`
"cat #{src_shell} > #{dst_file} && jpegoptim --all-progressive -q --strip-com --strip-exif --strip-iptc --stdout -- #{dst_shell}"
"cat #{src_shell} > #{dst_file} && jpegoptim --all-progressive -q --strip-com --strip-exif --strip-iptc -- #{dst_shell}"
when 'image/png', 'image/x-png'
"pngcrush -rem alla -q #{src_shell} #{dst_shell}"
when 'image/gif'
@@ -33,8 +30,13 @@ module Paperclip
return
end
run_and_verify!(cmd)
if dst_file.size == 0 # rubocop:disable Style/ZeroLengthPredicate
dst_file.close!
return nil
end
dst_file.tap(&:flush).tap(&:rewind)
dst_file
rescue StandardError => e
dst_file.close!
Paperclip.log("Error: cannot optimize: #{e}")