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?
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.