shrinerb / shrine

File Attachment toolkit for Ruby applications

Home Page:https://shrinerb.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Conditional validation of max image dimensions causes validation error

vanboom opened this issue · comments

commented

Attempting to validate width and height for image only mime types in an attacher that supports non-image mime types: jpg, png, gif, bmp, docx, pdf

From the docs...

Attacher.validate do
  if validate_mime_type_inclusion %w[image/jpeg image/png image/webp]
    validate_max_width 2000
    validate_max_height 2000
  end
end

Brief Description

Consider an attacher that allows uploading of image types and PDF file types.

Attempting to conditionally validate max width and height for image only attachments using the validate_mime_type_inclusion conditional as described in the docs, causes a validation error for mime types that are not in the inclusion list.

Expected behavior

  1. Only apply the max width and height validations to the mime type list.
  2. Skip the max width and height validations for mime types that are not in the inclusion list.

Actual behavior

Validation failed: File type must be one of: image/jpeg, image/png, image/webp, image/bmp, image/gif

Shrine version: 3.3.0

The docs that say that: https://shrinerb.com/docs/plugins/validation_helpers

They don't actually say what that code example is for fully. That example won't work on an attacher that supports non-image types, you are correct. But the docs don't exactly say they will... although I can see why you would get that idea.

Those docs are actually an example of not running the validate_max_width and validate_max_height UNLESS it's an image (to avoid an error raised!), but ALSO failing validation if it's not an image, yup.

I'm not sure what the docs should say to be more clear, but for what you want, try:

Attacher.validate do
  if file.mime_type&.start_with?("image/")
    validate_max_width 2000
    validate_max_height 2000
  end
end

Perhaps the example just needs some text explaining what it's meant to do: Validate that an attachment is one of those mime types, and then only if it is also run size validations.

commented

You are correct - the docs explain it correctly. What I was looking for was the method to perform the validation conditionally based upon a mime type check. Thanks for providing an example.

In general if you know or suspect what you have is a question rather than a bug report, please use the discussion forums rather than Github Issues. thanks!