igorkasyanchuk/active_storage_validations

Dimensions validations on saved attachment

gaelchriste opened this issue · 3 comments

Hello, in DimensionValidator is there a reason to validate image dimensions only when uploading attachment and not all the time ?

def validate_each(record, attribute, _value)
return true unless record.send(attribute).attached?
changes = record.attachment_changes[attribute.to_s]
return true if changes.blank?
files = Array.wrap(changes.is_a?(ActiveStorage::Attached::Changes::CreateMany) ? changes.attachables : changes.attachable)
files.each do |file|
metadata = Metadata.new(file).metadata
next if is_valid?(record, attribute, metadata)
break
end
end

Example:

user.avatar.attach(...) # image with wrong dimensions
user.valid? # => false
user.save(validate: false)
user.valid? # => true

Thank you!

@igorkasyanchuk any thoughts on this one?
I guess the validator should add an error when using .valid? as stated in Rails documentation

yeah, perhaps, but can create a bigger issue. If a file is stored in S3 for example, it means that to validate it we need to download it back and measure the dimensions. Probably we can mark this issue as "known issue". It can be handled somehow inside app logic.

wdyt?

@igorkasyanchuk I agree with @Mth0158 .valid? should raise an error in creation or update. I understand your point of view that it can be a issue in some case so maybe we can add an option to choose if we want to validate attachment only on creation ?