Validation
The validation plugin provides a framework for validating
attached files. For some useful validators, see the
validation_helpers plugin.
plugin :validationUsage
The Attacher.validate method is used to register a validation block, which
is called on attachment:
class VideoUploader < Shrine
Attacher.validate do
if file.duration > 5*60*60
errors << "duration must not be longer than 5 hours"
end
end
endattacher.assign(file)
attacher.errors #=> ["duration must not be longer than 5 hours"]The validation block is executed in context of a Shrine::Attacher instance:
class VideoUploader < Shrine
Attacher.validate do
self #=> #<Shrine::Attacher>
file #=> #<Shrine::UploadedFile>
record #=> #<Movie>
name #=> :video
context #=> { ... }
end
endInheritance
If you're subclassing an uploader that has validations defined, you can call
those validations via super():
class ApplicationUploader < Shrine
Attacher.validate { validate_max_size 5.megabytes }
endclass ImageUploader < ApplicationUploader
Attacher.validate do
super() # empty parentheses are required
validate_mime_type %w[image/jpeg image/png image/webp]
end
endValidation options
You can pass options to the validator via the :validate option:
attacher.assign(file, validate: { foo: "bar" })class MyUploader < Shrine
Attacher.validate do |**options|
options #=> { foo: "bar" }
end
endYou can also skip validation by passing validate: false:
attacher.assign(file, validate: false) # skips validationManual validation
You can also run validation manually via Attacher#validate:
attacher.set(uploaded_file) # doesn't trigger validation
attacher.validate # runs validation