You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

35 lines
1.3 KiB

  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.to_f)).round.to_i
  11. height = Math.sqrt(options[:pixels] * (@current_geometry.height.to_f / @current_geometry.width.to_f)).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?
  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. end
  28. end