2018-02-21 02:40:12 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module Paperclip
|
|
|
|
class LazyThumbnail < Paperclip::Thumbnail
|
|
|
|
def make
|
2018-02-21 23:28:19 +00:00
|
|
|
return File.open(@file.path) unless needs_convert?
|
2018-03-06 05:29:01 +00:00
|
|
|
|
2018-07-28 01:33:00 +00:00
|
|
|
if options[:geometry]
|
|
|
|
min_side = [@current_geometry.width, @current_geometry.height].min.to_i
|
|
|
|
options[:geometry] = "#{min_side}x#{min_side}#" if @target_geometry.square? && min_side < @target_geometry.width
|
|
|
|
elsif options[:pixels]
|
|
|
|
width = Math.sqrt(options[:pixels] * (@current_geometry.width.to_f / @current_geometry.height.to_f)).round.to_i
|
|
|
|
height = Math.sqrt(options[:pixels] * (@current_geometry.height.to_f / @current_geometry.width.to_f)).round.to_i
|
|
|
|
options[:geometry] = "#{width}x#{height}>"
|
|
|
|
end
|
2018-03-06 05:29:01 +00:00
|
|
|
|
2018-02-21 02:40:12 +00:00
|
|
|
Paperclip::Thumbnail.make(file, options, attachment)
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def needs_convert?
|
2018-09-17 18:24:46 +00:00
|
|
|
needs_different_geometry? || needs_different_format? || needs_metadata_stripping?
|
2018-02-21 02:40:12 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def needs_different_geometry?
|
2018-07-28 01:33:00 +00:00
|
|
|
(options[:geometry] && @current_geometry.width != @target_geometry.width && @current_geometry.height != @target_geometry.height) ||
|
|
|
|
(options[:pixels] && @current_geometry.width * @current_geometry.height > options[:pixels])
|
2018-02-21 02:40:12 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def needs_different_format?
|
|
|
|
@format.present? && @current_format != @format
|
|
|
|
end
|
2018-09-17 18:24:46 +00:00
|
|
|
|
|
|
|
def needs_metadata_stripping?
|
|
|
|
@attachment.instance.respond_to?(:local?) && @attachment.instance.local?
|
|
|
|
end
|
2018-02-21 02:40:12 +00:00
|
|
|
end
|
|
|
|
end
|