0

I have a field in a form where user can upload images or document (pdf, word, excel etc). How to tell Shrine uploader to process uploaded file base on it's filetype.

class FileUploader < Shrine

 plugin :processing
 plugin :versions   
 plugin :delete_raw 
 plugin :validation_helpers

if File_is_image # <------   what to write here?

   # do image processing
   process(:store) do |io, context|
    original = io.download
    pipeline = ImageProcessing::MiniMagick.source(original)
    size_800 = pipeline.resize_to_limit!(800, 800)
    size_300 = pipeline.resize_to_limit!(300, 300)
    original.close!
   { original: io, large: size_800, small: size_300 }
  end
 else
   #do non image file processing
 end
end

or is there any better way to do this?

Aipack
  • 94
  • 9
  • you can split the image name and get the extension and process according to that . i think `original` is the image object and you can do something like `ext = original.image.url.split('.')[1]` and process according to ext type. – Pardeep Saini Apr 13 '18 at 09:21

1 Answers1

0

The io object that's yielded to the process block is a Shrine::UploadedFile object, which contains all the metadata about the original file. You use this information to skip processing based on the MIME type:

IMAGE_TYPES = %w[image/jpeg image/png image/gif]

process(:store) do |io, context|
  next io unless IMAGE_TYPES.include?(io.mime_type)

  original = io.download
  pipeline = ImageProcessing::MiniMagick.source(original)
  size_800 = pipeline.resize_to_limit!(800, 800)
  size_300 = pipeline.resize_to_limit!(300, 300)
  original.close!

  { original: io, large: size_800, small: size_300 }
end

The next ruby keyword is used here to return early from a block.

Janko
  • 8,985
  • 7
  • 34
  • 51
  • Thanks @janko-m i believe you meant IMAGE_TYPES instead of MIME_TYPES ? also is it OK to have many file process (for video, image) in one Uploader class ? because for me its more convenient – Aipack Apr 15 '18 at 12:44
  • Thanks, corrected the `IMAGE_TYPES`. Yes, it's ok to have a single uploader handle multiple types of files, but I wouldn't generally recommend it, as you'll likely have lot of conditionals and might want to load different plugins depending on the size and type of the files. But definitely give it a go if you think it will be more convenient. – Janko Apr 17 '18 at 07:40