Conditional versions in Carrierwave

I am working on making a simple rotation + resizing on the downloaded image, but only if it is in landscape format. Otherwise, I just want the image to change. I also want to do this while keeping the same version name (I don't have "medium" and "medium_rotated"). While the rotation is working for me, but the problem is that I am uploading a non-landscape image, the job is for everyone. It works only for landscape images. Here are the relevant parts of my code. Any ideas?

-Benny

class FloorPlanPhotoUploader < CarrierWave::Uploader::Base .... version :medium, :if => :is_landscape? do process :rotate_cw end version :medium do process :resize_and_pad => [ 260, 360, :white, 'Center'] end def is_landscape? picture file = (picture.is_a? CarrierWave::Storage::Fog::File) ? picture.public_url : picture.file image = MiniMagick::Image.open(file) image[:width] > image[:height] end def rotate_cw manipulate! do |img| img.rotate "90>" img = yield(img) if block_given? img end end .... end 
+4
source share
2 answers

The problem is that you double-defined the version :medium . It strikes:

 ..., :if => is_landscape? 

which for non-landscape images returns false. As a result, nothing is done. The second version :medium declaration that you have there never starts because you cannot declare two versions with the same name, so it just skipped completely.

What you need to do is create only one version with the name :medium and conditionally handle the clockwise rotation. Sort of:

 class FloorPlanPhotoUploader < CarrierWave::Uploader::Base ... version :medium do process :rotate_cw, :if => :is_landscape? process :resize_and_pad => [ 260, 360, :white, 'Center'] end ... end 

Thus, you can link several processing steps in one version. Here is a great tutorial that touches on this topic in more detail.

+3
source

Here is the solution:

 version :medium do process :rotate_cw, if: ->( uploader, args ) { uploader.model.is_landscape? } process :resize_and_pad => [ 260, 360, :white, 'Center'] end 
+1
source

Source: https://habr.com/ru/post/1402546/


All Articles