lazy_thumbnail.rb 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. # frozen_string_literal: true
  2. module Paperclip
  3. class LazyThumbnail < Paperclip::Thumbnail
  4. def make
  5. return File.open(@file.path) unless needs_convert?
  6. if options[:geometry]
  7. min_side = [@current_geometry.width, @current_geometry.height].min.to_i
  8. options[:geometry] = "#{min_side}x#{min_side}#" if @target_geometry.square? && min_side < @target_geometry.width
  9. elsif options[:pixels]
  10. width = Math.sqrt(options[:pixels] * (@current_geometry.width.to_f / @current_geometry.height)).round.to_i
  11. height = Math.sqrt(options[:pixels] * (@current_geometry.height.to_f / @current_geometry.width)).round.to_i
  12. options[:geometry] = "#{width}x#{height}>"
  13. end
  14. Paperclip::Thumbnail.make(file, options, attachment)
  15. end
  16. private
  17. def needs_convert?
  18. needs_different_geometry? || needs_different_format? || needs_metadata_stripping?
  19. end
  20. def needs_different_geometry?
  21. (options[:geometry] && @current_geometry.width != @target_geometry.width && @current_geometry.height != @target_geometry.height) ||
  22. (options[:pixels] && @current_geometry.width * @current_geometry.height > options[:pixels])
  23. end
  24. def needs_different_format?
  25. @format.present? && @current_format != @format
  26. end
  27. def needs_metadata_stripping?
  28. @attachment.instance.respond_to?(:local?) && @attachment.instance.local?
  29. end
  30. end
  31. end