我有一个表单中的字段,用户可以上传图像或文档(pdf,word,excel等)。如何告诉Shrine上传者根据它的文件类型处理上传的文件。
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
还是有更好的方法吗?
答案 0 :(得分:0)
产生于进程块的io
对象是Shrine::UploadedFile
对象,其中包含有关原始文件的所有元数据。您可以使用此信息跳过基于MIME类型的处理:
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
此处使用next
ruby关键字从块中提前返回。