igorkasyanchuk/active_storage_validations
Sobre
Faça assim => validates :photos, attached: true, content_type: ['image/png', 'image/jpg', 'image/jpeg'], size: { less_than: 500.kilobytes }, limit: { min: 1, max: 3 }, aspect_ratio: :landscape, dimension: { width: { in: 800..1600 }
Design e mídiaCrescimento medido de estrelas
- em 24 h
- 0
- em 7 dias
- 0
- em 15 dias
- +1
- em 1 mês
- +1
Variações líquidas em períodos sobrepostos, não totais diários. Medições ausentes ficam em branco. Estrelas indicam interesse, não qualidade.
README.md
OriginalActive Storage Validations
Active Storage Validations is a gem that allows you to add validations for Active Storage attributes.
This gem is doing it right for you! Just use validates :avatar, attached: true, content_type: 'image/png' and that's it!
Table of Contents
- Getting started
- Validators
- Upgrading
- Internationalization (I18n)
- Test matchers
- Contributing
- Additional information
Getting started
Installation
Active Storage Validations work with Rails 7.0.1 onwards and Ruby 3.3 onwards. Add this line to your application's Gemfile:
gem 'active_storage_validations'
And then execute:
$ bundle
Error messages (I18n)
Once you have installed the gem, I18n error messages will be added automatically to your app. See Internationalization (I18n) section for more details.
Using image metadata validators
Optionally, to use the image metadata validators (dimension, aspect_ratio and processable_file), you will have to add one of the corresponding gems:
gem 'ruby-vips', '>= 2.1.0'
# Or
gem 'mini_magick', '>= 4.9.5'
Plus, you have to be sure to have the corresponding command-line tool installed on your system (libvips for ruby-vips, or ImageMagick for mini_magick — both locally and in CI / production).
We recommend libvips (ruby-vips + config.active_storage.variant_processor = :vips) for these validators. Rails already defaults Active Storage variants to libvips (ActiveStorage::Variant), and our image processor benchmarks show cold metadata analysis is about 8× to 24× faster than MiniMagick/ImageMagick on the same machine and fixtures, depending on the machine. Warm validations (cached asv_* metadata) are similar for both.
Using video and audio metadata validators
To use the video and audio metadata validators (dimension, aspect_ratio, processable_file, duration and with_audio), you will not need to add any gems. However you will need to have the ffmpeg command-line tool installed on your system (once again, be sure to have it installed both on your local and in your CI / production environments).
Using pdf metadata validators
To use the pdf metadata validators (dimension, aspect_ratio, processable_file and pages), you will not need to add any gems. However you will need to have the poppler tool installed on your system (once again, be sure to have it installed both on your local and in your CI / production environments).
Using content type spoofing protection validator option
To use the spoofing_protection option with the content_type validator:
- Default backend (
true/:file): the UNIXfilecommand (usually preinstalled on UNIX systems) - Magika backend (
:magika): the Google Magika CLI — install viabrew install magika, their install script,cargo install --locked magika-cli, orpipx install magika
Both backends are optional system tools (not Ruby gems). Prefer :magika when you can install the CLI — it is generally more accurate than file, especially on textual / ambiguous formats. Be sure to install Magika in CI / production if you enable :magika.
If you want some inspiration about how to add imagemagick, libvips, ffmpeg, poppler or magika to your docker image, you can check how we do it for the gem CI (https://github.com/igorkasyanchuk/active_storage_validations/blob/master/.github/workflows/main.yml)
Configuration
Optional global settings can go in an initializer. Example template:
# config/initializers/active_storage_validations.rb
ActiveStorageValidations.configure do |config|
# Infer HTML accept= on file_field from content_type validators (default: true)
# config.infer_file_field_accept = false
# Max time for external analyzer commands: ffprobe, pdfinfo, file, magika, ImageMagick identify, libvips
# (default: 10.seconds; set to nil to disable)
# config.command_timeout = 10.seconds
end
# Optional: monitor analyzer timeouts
# ActiveSupport::Notifications.subscribe("timeout.active_storage_validations") do |*args|
# event = ActiveSupport::Notifications::Event.new(*args)
# Rails.logger.warn("[ASV] command timeout: #{event.payload}")
# end
# Optional: monitor how long metadata / content type analysis takes
# ActiveSupport::Notifications.subscribe("analyze.active_storage_validations") do |*args|
# event = ActiveSupport::Notifications::Event.new(*args)
# Rails.logger.info("[ASV] analyzed: #{event.payload}")
# end
The gem emits two ActiveSupport::Notifications events:
| Event | Payload | Emitted |
|---|---|---|
analyze.active_storage_validations |
analyzer, command, timeout, timed_out, duration, plus the file keys below |
Every time an analyzer command runs (i.e. on a cache miss) |
timeout.active_storage_validations |
analyzer, command, timeout, plus the file keys below |
Only when a command exceeds its deadline |
Both payloads name the analyzed file, so a slow or timed out analysis can be traced back to its upload: filename, content_type (as declared), byte_size (nil for an IO that cannot tell) and blob_key (nil until the file is an ActiveStorage::Blob).
command_timeout bounds metadata analysis used by dimension, aspect_ratio, duration, with_audio, pages, processable_file, and content_type (with spoofing_protection). When a command times out, analysis fails closed and the validator adds its usual error (file_not_processable / media_metadata_missing / audio_missing / content-type errors) — there is no separate timeout error message. The exception is with_audio: { with: false }: a file that could not be analyzed has no audio track found, so it passes.
The 10s default is enough for typical uploads. Raise it (or set nil) if you analyze very large videos/PDFs, especially on slow or network storage — otherwise those files can start failing validation after upgrade. See upgrade to 4.x.
Per-validator override (applies to the analysis triggered by that validator; the first analysis for a blob is cached):
validates :video, duration: { less_than: 5.minutes, timeout: 30.seconds }
Notes:
- Setting
command_timeout(or per-validatortimeout:) tonildisables the deadline - ImageMagick analysis runs
identifythrough the same killable command runner (MiniMagick is only used to build the argv) - For libvips, a timeout may not immediately free the Ruby thread stuck in FFI/C; the validation still fails closed and emits
timeout.active_storage_validations - On Windows there are no POSIX process groups: a timed out command is killed directly (its own child processes, if any, are not), without the TERM grace period
Validators
List of validators:
- Attached: validates if file(s) attached
- Limit: validates number of uploaded files
- Content type: validates file content type
- Size: validates file size
- Total size: validates total file size for several files
- Dimension: validates image / video dimensions
- Duration: validates video / audio duration
- With audio: validates whether a video / audio file contains an audio track
- Aspect ratio: validates image / video aspect ratio
- Processable file: validates if a file can be processed
- Pages: validates pdf number of pages
Attachments marked for destruction
Files whose attachment is marked for destruction (e.g. nested attributes with _destroy) are not validated: they will be gone once the record is saved. attached still fails when every attachment is marked for destruction.
Proc usage
Every validator can use procs instead of values in all the validator examples:
class User < ApplicationRecord
has_many_attached :files
validates :files, limit: { max: -> (record) { record.admin? ? 100 : 10 } }
end
Static options are checked when the model class loads; a proc's result is only known at validation time, so an unsupported value returned by a proc ("image/jpg" for content_type, :sqaure for aspect_ratio) raises the same ArgumentError from valid? instead of silently rejecting every file.
A proc is called once per validation, however many files are attached, so a proc that runs a query does not make one query per file.
timeout, precision and spoofing_protection take static values only: they set how files are analyzed, not what is accepted.
Performance optimization
Some validators rely on an expensive operation (metadata analysis and content type analysis). To mitigate the performance cost, the gem leverages the ActiveStorage::Blob.metadata method to store retrieved metadata. Therefore, once the file has been analyzed by our gem, the expensive analysis operation will not be triggered again for new validations.
As stated in the Rails documentation: "Blobs are intended to be immutable in so far as their reference to a specific file goes". We based our performance optimization on the same assumption, so if you do not follow it, the gem will not work as expected.
This also covers metadata the analyzer cannot extract from a given file (e.g. a duration validation on an image): the gem remembers that the value is unavailable, so the validation keeps failing with media_metadata_missing but the file is only analyzed once. Files that yield no metadata at all — missing command-line tool, timed out command, unreadable file — are not remembered and get analyzed again on the next validation.
Clients cannot pre-fill this cache to skip the analysis (e.g. through Rails' direct upload endpoint, which accepts metadata: { custom: … }): a new blob drops asv_* keys when it is initialized, so only the gem writes them.
To force re-analysis of a persisted blob, call blob.remove_active_storage_validations_metadata!. That clears asv_* keys and, when the blob is already saved, writes the change with save! (the blob callbacks run) so reload does not restore them. Non-asv_* custom metadata is kept.
To clear the cache of many blobs at once (e.g. after an upgrade that teaches an analyzer to read files it could not before), run the rake task or its Ruby equivalent. A cleared blob is analyzed again the next time it is validated (attached again, or another file added to its has_many_attached); existing records are not re-validated. Both skip the blob callbacks, so attached records are not touched:
bin/rails active_storage_validations:remove_metadata
bin/rails active_storage_validations:remove_metadata CONTENT_TYPE=video/webm,audio/webm # only these content types
ActiveStorageValidations.remove_metadata! # every blob, returns the number of blobs cleared
ActiveStorageValidations.remove_metadata!(ActiveStorage::Blob.where(content_type: "video/webm")) # any blob relation
Attached
Validates if the attachment is present.
Options
The attached validator has no options.
Examples
Use it like this:
class User < ApplicationRecord
has_one_attached :avatar
validates :avatar, attached: true # ensures that avatar has an attached file
end
Error messages (I18n)
en:
errors:
messages:
blank: "can't be blank"
The error message for this validator relies on Rails own blank error message.
Limit
Validates the number of uploaded files.
Options
The limit validator has 2 possible options:
min: defines the minimum allowed number of filesmax: defines the maximum allowed number of files
Attachments marked for destruction are ignored, so they do not count against :min / :max.
Examples
Use it like this:
class User < ApplicationRecord
has_many_attached :certificates
validates :certificates, limit: { min: 1, max: 10 } # restricts the number of files to between 1 and 10
validates :certificates, limit: { min: 1, max: ->(record) { record.admin? ? 100 : 10 } } # mix a static bound with a Proc
validates :certificates, limit: { max: 0 } # freeze uploads (empty is valid, any file is not)
end
Error messages (I18n)
en:
errors:
messages:
limit_out_of_range:
zero: "no files attached (must have between %{min} and %{max} files)"
one: "only 1 file attached (must have between %{min} and %{max} files)"
other: "total number of files must be between %{min} and %{max} files (there are %{count} files attached)"
limit_min_not_reached:
zero: "no files attached (minimum is %{min})"
one: "only 1 file attached (minimum is %{min})"
other: "%{count} files attached (minimum is %{min})"
limit_max_exceeded:
zero: "no files attached (maximum is %{max})"
one: "too many files attached (maximum is %{max}, got %{count})"
other: "too many files attached (maximum is %{max}, got %{count})"
The limit validator error messages expose 3 values that you can use:
mincontaining the minimum allowed number of files (e.g.1)maxcontaining the maximum allowed number of files (e.g.10)countcontaining the current number of files (e.g.5)
Content type
Validates if the attachment has an allowed content type.
Options
The content_type validator has several possible options:
with: defines the allowed content type (string, symbol, regex or media type wildcard)in: defines the allowed content types (array of strings, symbols, regexes or media type wildcards)spoofing_protection: enables content type spoofing protection (falseby default). Allowed values:true/:file(UNIXfileCLI),:magika(Google Magika CLI)timeout: overrides the global analyzer command timeout when spoofing protection runsfileormagika
As mentioned above, this validator can define content types in several ways:
- String:
image/pngorpng - Symbol:
:png - Regex:
/\Avideo\/.*\z/ - Media type wildcard:
"image/*", as in the HTMLacceptattribute. It allows every image type, and error messages show it asimage/*(a regex shows its source)
Examples
Use it like this:
class User < ApplicationRecord
has_one_attached :avatar
validates :avatar, content_type: 'image/png' # only allows PNG images
validates :avatar, content_type: :png # only allows PNG images, same as { with: :png }
validates :avatar, content_type: /\Avideo\/.*\z/ # only allows video files
validates :avatar, content_type: "image/*" # only allows images
validates :avatar, content_type: ["image/*", :pdf] # allows images and PDF files
validates :avatar, content_type: ['image/png', 'image/jpeg'] # only allows PNG and JPEG images
validates :avatar, content_type: { in: [:png, :jpeg], spoofing_protection: true } # UNIX `file` backend (same as :file)
validates :avatar, content_type: { in: [:png, :jpeg], spoofing_protection: :magika } # Google Magika CLI backend
# Stronger protection for media/PDF: sniff + parse
validates :avatar, content_type: { in: [:png, :jpeg], spoofing_protection: true }, processable_file: true
end
HTML accept attribute (FormBuilder)
When using Rails' FormBuilder#file_field, the gem automatically sets the HTML accept attribute from your content_type validators. This improves UX by filtering selectable files in the browser dialog. It is only a frontend hint: a malicious user can still submit disallowed types, so keep the backend validation.
class User < ApplicationRecord
has_one_attached :avatar
validates :avatar, content_type: ['image/png', 'image/jpeg']
end
<%= form_with model: @user do |f| %>
<%= f.file_field :avatar %>
<%# => <input type="file" accept="image/png,image/jpeg" ...> %>
<% end %>
Explicit accept values are never overridden. You can also disable inference:
<%# Per field %>
<%= f.file_field :avatar, infer_accept: false %>
<%# Or set a custom accept value %>
<%= f.file_field :avatar, accept: "image/*" %>
# Globally — see [Configuration](#configuration) for a full initializer template
ActiveStorageValidations.infer_file_field_accept = false
# Equivalent:
ActiveStorageValidations.configure { |config| config.infer_file_field_accept = false }
Notes:
- Media type wildcards (
"image/*") are passed as they are, and broad MIME-type regexes of the form/\Aimage\/.*\z/(orvideo/audio/ etc.) are inferred asimage/* - Other regexes (e.g.
/\Aimage\/(png|gif)\z/) cannot be reliably represented inaccept - Proc / dynamic
content_typeoptions are not evaluated: they are not called while the form renders, because their result can depend on record state that is only set on submit, and a raising proc would break the whole view for what is merely a frontend hint. Backend validation is unchanged; pass a customaccept:on those fields if you want the picker filtered - A validator with such a regex or Proc in its list sets no
acceptat all: listing only its other types would hide files it allows. Anothercontent_typevalidator on the same attribute still setsaccept, since every file must pass it - Conditional validators (
if:/unless:,on:/except_on:) are not evaluated: their content types are always included inaccept, even when the condition or context would skip the validator for that record. Backend validation is unchanged; useinfer_accept: false(or a customaccept:) if the picker must match the active conditions
Content type shorthands
If you choose to use a content_type 'shorthand' (like png), note that it will be converted to a full content type using Marcel::MimeType.for under the hood. Therefore, you should check if the content_type is registered by Marcel::EXTENSIONS. Aliases such as audio/x-flac or application/x-msaccess are valid options and match uploads of their canonical type (audio/flac, application/vnd.ms-access). If the type is not registered, you can register it by adding the following code to your config/initializers/mime_types.rb file:
Marcel::MimeType.extend "application/ino", extensions: %w(ino), parents: "text/plain" # Registering arduino INO files
Be sure to at least include one of the extensions, parents or magic options, otherwise the content type will not be registered.
Content type spoofing protection
By default, the gem does not prevent content type spoofing. Enable it with spoofing_protection:
validates :avatar, content_type: { in: [:png, :jpeg], spoofing_protection: true } # => :file (UNIX file CLI)
validates :avatar, content_type: { in: [:png, :jpeg], spoofing_protection: :file } # explicit
validates :avatar, content_type: { in: [:png, :jpeg], spoofing_protection: :magika } # Google Magika CLI
Override binary paths with ActiveStorage.paths[:file] / ActiveStorage.paths[:magika] if needed.
What is content type spoofing?
File content type spoofing happens when an ill-intentioned user uploads a file which hides its true content type by faking its extension and its declared content type value. For example, a user may try to upload a .exe file (application/x-msdownload content type) dissimulated as a .jpg file (image/jpeg content type).
How do we prevent it?
Spoofing protection compares the declared Active Storage content type to a type detected by a sniffer CLI, then uses Marcel parent types so near-matches still pass:
:file(default) — UNIXfile/ libmagic, mostly magic bytes / headers. Zero extra install on most UNIX systems.:magika— Google Magika CLI (ML sniffer; samples begin/middle/end of the file). Generally more accurate thanfile, especially on textual / ambiguous formats (Google reports ~99% F1 vs ~88% forfile --mimeon overlapping types). Prefer:magikawhen you can install the CLI.
Neither backend fully parses the file. They do not load the whole file into RAM. For already-persisted blobs (e.g. remote storage), the analyzer still downloads the blob to a local tempfile before sniffing. That download is streamed in chunks to disk, but it can still be costly for very large files. Local path uploads are analyzed in place.
Detected types are cached on the blob as asv_content_type + asv_content_type_backend. Switching backend re-analyzes. Legacy blobs that only have asv_content_type (no backend key) are treated as :file and keep using the cache — they are not re-analyzed. New (unsaved) blobs keep asv_* in memory until the record is saved; already-persisted blobs write the cache immediately so it survives reload.
Sniffers will not always return the exact same MIME as Active Storage (AS uses first ~4kb + filename + extension). Close parent types are accepted via Marcel::TYPE_PARENTS (e.g. video/x-ms-wmv vs video/x-ms-asf). On Marcel 2 (Rails 8.2+), aliased types such as text/xml / application/xml and audio/x-m4a / audio/mp4 are also treated as equivalent.
For stronger protection on images / video / audio / PDF, combine sniffing with parse validation:
validates :avatar, content_type: { in: [:png, :jpeg], spoofing_protection: true }, processable_file: true
Edge cases
The difficulty to accurately predict a mime type may generate false positives, if so there are several solutions available:
- Try the other sniffer backend (
:filevs:magika) - For media/PDF that sniffers misidentify but that open correctly, add
processable_file: true - If the ActiveStorage blob content type is closely related to the detected content type, enhance
Marcel::TYPE_PARENTSmapping usingMarcel::MimeType.extend "application/x-rar-compressed", parents: %(application/x-rar)in theconfig/initializers/mime_types.rbfile. (Please drop an issue so we can add it to the gem for everyone!) - If needed, disable spoofing protection in the validator, and please drop us an issue so we can fix it for everyone!
Error messages (I18n)
en:
errors:
messages:
content_type_invalid:
one: "has an invalid content type (authorized content type is %{authorized_human_content_types})"
other: "has an invalid content type (authorized content types are %{authorized_human_content_types})"
content_type_spoofed:
one: "has a content type that is not equivalent to the one that is detected through its content (authorized content type is %{authorized_human_content_types})"
other: "has a content type that is not equivalent to the one that is detected through its content (authorized content types are %{authorized_human_content_types})"
attachment_missing: "is missing its attachment"
attachment_missing is added when the file of an attachment cannot be found on the storage service while spoofing protection reads it.
The content_type validator error messages expose 7 values that you can use:
content_typecontaining the content type of the sent file (e.g.image/png)human_content_typecontaining a more user-friendly version of the sent file content type (e.g. 'TXT' for 'text/plain')detected_content_typecontaining the detected content type of the sent file usingspoofing_protectionoption (e.g.image/png)detected_human_content_typecontaining a more user-friendly version of the sent file detected content type usingspoofing_protectionoption (e.g. 'TXT' for 'text/plain')authorized_human_content_typescontaining the list of authorized content types (e.g. 'PNG, JPG' for['image/png', 'image/jpeg'], 'MP3, MOV' for[:mp3, :mov], 'image/*' for"image/*")countcontaining the number of authorized content types (e.g.2)filenamecontaining the filename
Size
Validates each attached file size.
Options
The size validator has 6 possible options:
less_than: defines the strict maximum allowed file sizeless_than_or_equal_to: defines the maximum allowed file sizegreater_than: defines the strict minimum allowed file sizegreater_than_or_equal_to: defines the minimum allowed file sizebetween: defines the allowed file size rangeequal_to: defines the allowed file size
Pass one comparison option per validator (between covers a range); add a second validator to combine others.
Attachments marked for destruction are ignored, so they do not count against the bound.
Examples
Use it like this:
class User < ApplicationRecord
has_one_attached :avatar
validates :avatar, size: { less_than: 2.megabytes } # restricts the file size to < 2MB
validates :avatar, size: { less_than_or_equal_to: 2.megabytes } # restricts the file size to <= 2MB
validates :avatar, size: { greater_than: 1.kilobyte } # restricts the file size to > 1KB
validates :avatar, size: { greater_than_or_equal_to: 1.kilobyte } # restricts the file size to >= 1KB
validates :avatar, size: { between: 1.kilobyte..2.megabytes } # restricts the file size to between 1KB and 2MB
validates :avatar, size: { equal_to: 1.megabyte } # restricts the file size to exactly 1MB
end
Best practices
It is always a good practice to limit the maximum file size to a reasonable value (like 2MB for avatar images). This helps prevent server storage issues, reduces upload/download times, and ensures better performance. Large files can consume excessive bandwidth and storage space, potentially impacting both server resources and user experience.
Plus, not setting a size limit inside your Rails app might lead into your server throwing a 413 Content Too Large error, which is not as nice as a Rails validation error.
Error messages (I18n)
en:
errors:
messages:
file_size_not_less_than: "file size must be less than %{max} (current size is %{file_size})"
file_size_not_less_than_or_equal_to: "file size must be less than or equal to %{max} (current size is %{file_size})"
file_size_not_greater_than: "file size must be greater than %{min} (current size is %{file_size})"
file_size_not_greater_than_or_equal_to: "file size must be greater than or equal to %{min} (current size is %{file_size})"
file_size_not_between: "file size must be between %{min} and %{max} (current size is %{file_size})"
file_size_not_equal_to: "file size must be equal to %{exact} (current size is %{file_size})"
The size validator error messages expose 5 values that you can use:
file_sizecontaining the current file size (e.g.1.5MB)mincontaining the minimum allowed file size (e.g.1KB)exactcontaining the allowed file size (e.g.1MB)maxcontaining the maximum allowed file size (e.g.2MB; for exclusivebetween:ranges, the last included value)filenamecontaining the current file name
Total size
Validates the total file size for several files.
Options
The total_size validator has 6 possible options:
less_than: defines the strict maximum allowed total file sizeless_than_or_equal_to: defines the maximum allowed total file sizegreater_than: defines the strict minimum allowed total file sizegreater_than_or_equal_to: defines the minimum allowed total file sizebetween: defines the allowed total file size rangeequal_to: defines the allowed total file size
Pass one comparison option per validator (between covers a range); add a second validator to combine others.
Attachments marked for destruction are ignored, so they do not count against the total.
Examples
Use it like this:
class User < ApplicationRecord
has_many_attached :certificates
validates :certificates, total_size: { less_than: 10.megabytes } # restricts the total size to < 10MB
validates :certificates, total_size: { less_than_or_equal_to: 10.megabytes } # restricts the total size to <= 10MB
validates :certificates, total_size: { greater_than: 1.kilobyte } # restricts the total size to > 1KB
validates :certificates, total_size: { greater_than_or_equal_to: 1.kilobyte } # restricts the total size to >= 1KB
validates :certificates, total_size: { between: 1.kilobyte..10.megabytes } # restricts the total size to between 1KB and 10MB
validates :certificates, total_size: { equal_to: 1.megabyte } # restricts the total file size to exactly 1MB
end
Error messages (I18n)
en:
errors:
messages:
total_file_size_not_less_than: "total file size must be less than %{max} (current size is %{total_file_size})"
total_file_size_not_less_than_or_equal_to: "total file size must be less than or equal to %{max} (current size is %{total_file_size})"
total_file_size_not_greater_than: "total file size must be greater than %{min} (current size is %{total_file_size})"
total_file_size_not_greater_than_or_equal_to: "total file size must be greater than or equal to %{min} (current size is %{total_file_size})"
total_file_size_not_between: "total file size must be between %{min} and %{max} (current size is %{total_file_size})"
total_file_size_not_equal_to: "total file size must be equal to %{exact} (current size is %{total_file_size})"
The total_size validator error messages expose 4 values that you can use:
total_file_sizecontaining the current total file size (e.g.1.5MB)mincontaining the minimum allowed total file size (e.g.1KB)exactcontaining the allowed total file size (e.g.1MB)maxcontaining the maximum allowed total file size (e.g.2MB; for exclusivebetween:ranges, the last included value)
Dimension
Validates the dimension of the attached image / video files. It can also be used for pdf files, but it will only analyze the pdf first page, and will assume a DPI of 72. (be sure to have the right dependencies installed as mentioned in Getting started)
Options
The dimension validator has several possible options:
width: defines the allowed width (integer)min: defines the minimum allowed width (integer)max: defines the maximum allowed width (integer)in: defines the allowed width range (range)
height: defines the allowed height (integer)min: defines the minimum allowed height (integer)max: defines the maximum allowed height (integer)in: defines the allowed height range (range)
min: defines the minimum allowed width and height (range)max: defines the maximum allowed width and height (range)timeout: overrides the global analyzer command timeout for this validation
At boot, the validator checks that at least one of width, height, min and max is given, and that in: and the top-level min / max are Ranges (or Procs). Other keys in a width / height Hash (a typo such as { minimum: 1000 }) are ignored, so double-check them: such an option validates nothing.
Width and height are the displayed ones: an image whose EXIF orientation turns it a quarter (5 to 8) is measured rotated, a video by its rotation and display aspect ratio, a PDF page by its /Rotate, and an animated GIF by its canvas.
Examples
Use it like this:
class User < ApplicationRecord
has_one_attached :avatar
validates :avatar, dimension: { width: 100 } # restricts the width to 100 pixels
validates :avatar, dimension: { width: { min: 80, max: 100 } } # restricts the width to between 80 and 100 pixels
validates :avatar, dimension: { width: { in: 80..100 } } # restricts the width to between 80 and 100 pixels
validates :avatar, dimension: { width: { in: 80...100 } } # same, but exclusive end (80–99), matching Ruby `Range`
validates :avatar, dimension: { height: 100 } # restricts the height to 100 pixels
validates :avatar, dimension: { height: { min: 600, max: 1800 } } # restricts the height to between 600 and 1800 pixels
validates :avatar, dimension: { height: { in: 600..1800 } } # restricts the height to between 600 and 1800 pixels
validates :avatar, dimension: { min: 80..600, max: 100..1800 } # restricts the width to between 80 and 100 pixels, and the height to between 600 and 1800 pixels
end
Error messages (I18n)
en:
errors:
messages:
dimension_min_not_included_in: "must be greater than or equal to %{width} x %{height} pixels"
dimension_max_not_included_in: "must be less than or equal to %{width} x %{height} pixels"
dimension_width_not_included_in: "width is not included between %{min} and %{max} pixels"
dimension_height_not_included_in: "height is not included between %{min} and %{max} pixels"
dimension_width_not_greater_than_or_equal_to: "width must be greater than or equal to %{length} pixels"
dimension_height_not_greater_than_or_equal_to: "height must be greater than or equal to %{length} pixels"
dimension_width_not_less_than_or_equal_to: "width must be less than or equal to %{length} pixels"
dimension_height_not_less_than_or_equal_to: "height must be less than or equal to %{length} pixels"
dimension_width_not_equal_to: "width must be equal to %{length} pixels"
dimension_height_not_equal_to: "height must be equal to %{length} pixels"
media_metadata_missing: "is not a valid media file"
attachment_missing: "is missing its attachment"
The dimension validator error messages expose 6 values that you can use:
mincontaining the minimum width or height allowedmaxcontaining the maximum width or height allowed (for exclusivein:ranges, the last included value:400...600reports599)widthcontaining the minimum or maximum width allowedheightcontaining the minimum or maximum height allowedlengthcontaining the exact width or height allowedfilenamecontaining the current filename in error
Duration
Validates the duration of the attached audio / video files. (be sure to have the right dependencies installed as mentioned in Using video and audio metadata validators)
Options
The duration validator has several possible options:
less_than: defines the strict maximum allowed file durationless_than_or_equal_to: defines the maximum allowed file durationgreater_than: defines the strict minimum allowed file durationgreater_than_or_equal_to: defines the minimum allowed file durationbetween: defines the allowed file duration rangeequal_to: defines the allowed durationtimeout: overrides the global analyzer command timeout for this validationprecision: the number of decimal places of a second the duration is rounded to before it is compared and shown in messages, an Integer from0to3(default3, milliseconds)
Pass one comparison option per validator (between covers a range); add a second validator to combine others.
Duration is compared to the millisecond by default (the analyzer no longer rounds to 0.1s): a 1.96s file passes less_than: 2.seconds. Encoders pad audio and video, so a "5-second" file often lasts 5.029s and fails equal_to: 5.seconds: round it with precision: 1 (tenths, as before 4.2) or precision: 0 (whole seconds). A file lasts as long as its longest track (the container, its audio and its video).
Recordings made in the browser with the MediaRecorder API (WebM from Chrome / Firefox) carry no duration in their header: their duration is read from their last frame instead.
Examples
Use it like this:
class User < ApplicationRecord
has_one_attached :intro_song
validates :intro_song, duration: { less_than: 2.minutes } # restricts the file duration to < 2 minutes
validates :intro_song, duration: { less_than_or_equal_to: 2.minutes } # restricts the file duration to <= 2 minutes
validates :intro_song, duration: { greater_than: 1.second } # restricts the file duration to > 1 second
validates :intro_song, duration: { greater_than_or_equal_to: 1.second } # restricts the file duration to >= 1 second
validates :intro_song, duration: { between: 1.second..2.minutes } # restricts the file duration to between 1 second and 2 minutes
validates :intro_song, duration: { equal_to: 1.minute } # restricts the duration to exactly 1 minute
validates :intro_song, duration: { equal_to: 5.seconds, precision: 1 } # a 5.029s file passes: compared as 5.0s
validates :intro_song, duration: { less_than: 5.minutes, timeout: 5.seconds } # custom analyzer timeout
end
Error messages (I18n)
en:
errors:
messages:
duration_not_less_than: "duration must be less than %{max} (current duration is %{duration})"
duration_not_less_than_or_equal_to: "duration must be less than or equal to %{max} (current duration is %{duration})"
duration_not_greater_than: "duration must be greater than %{min} (current duration is %{duration})"
duration_not_greater_than_or_equal_to: "duration must be greater than or equal to %{min} (current duration is %{duration})"
duration_not_between: "duration must be between %{min} and %{max} (current duration is %{duration})"
duration_not_equal_to: "duration must be equal to %{exact} (current duration is %{duration})"
media_metadata_missing: "is not a valid media file"
attachment_missing: "is missing its attachment"
media_metadata_missing is added when the file's duration cannot be read (not an audio / video file, missing ffprobe, timed out analysis), and attachment_missing when the file of an attachment cannot be found on the storage service.
The duration validator error messages expose 5 values that you can use:
durationcontaining the current duration size, to the millisecond (e.g.2 minutes,5.029 seconds)mincontaining the minimum allowed duration size (e.g.1 second)exactcontaining the allowed duration (e.g.3 seconds)maxcontaining the maximum allowed duration (e.g.2 minutes; for exclusivebetween:ranges, the last included value, so2.seconds...7.secondsreports6.999 seconds)filenamecontaining the current file name
Duration values are humanized in the current locale (e.g. 1 minute et 30 secondes in French) through the active_storage_validations.duration keys shipped with every bundled locale: one one / other pair per unit (plus the few / many forms Russian, Ukrainian and Polish need with rails-i18n pluralization rules) (years, months, weeks, days, hours, minutes, seconds) plus the sentence connectors. Locales the gem does not ship fall back to the English wording. Override them in your application locales like any other key:
en:
active_storage_validations:
duration:
seconds:
one: "%{count} second"
other: "%{count} seconds"
connectors:
words_connector: ", "
two_words_connector: " and "
last_word_connector: ", and "
With audio
Validates whether attached video / audio files contain an audio track. (be sure to have the right dependencies installed as mentioned in Using video and audio metadata validators)
Options
The with_audio validator supports:
with:truerequires an audio track andfalserejects onetimeout: overrides the global analyzer command timeout for this validation
Examples
Use it like this:
class User < ApplicationRecord
has_one_attached :video
has_one_attached :silent_video
validates :video, with_audio: true
validates :silent_video, with_audio: { with: false }
validates :video, with_audio: { with: ->(record) { record.needs_audio? } }
validates :video, with_audio: { timeout: 5.seconds }
end
Rails treats a bare with_audio: false as a disabled validator. Use the hash form with_audio: { with: false } to reject files that contain audio.
Files that cannot contain an audio stream at all (images, pdfs) are treated as having no audio track: they fail with_audio: true and pass with_audio: { with: false }. So does a file that could not be analyzed (missing ffprobe, timed out analysis).
Error messages (I18n)
en:
errors:
messages:
audio_missing: "must have an audio track"
audio_present: "must not have an audio track"
attachment_missing: "is missing its attachment"
The with_audio validator error message exposes the filename value containing the current file name.
Aspect ratio
Validates the aspect ratio of the attached image / video files. It can also be used for pdf files, but it will only analyze the pdf first page. (be sure to have the right dependencies installed as mentioned in Getting started)
Options
The aspect_ratio validator has several options:
with: defines the allowed aspect ratio (e.g.:is_16_9)in: defines the allowed aspect ratios (e.g.%i[square landscape])timeout: overrides the global analyzer command timeout for this validation
This validator can define aspect ratios in several ways:
- Symbols:
- prebuilt aspect ratios:
:square,:portrait,:landscape - ISO 216 paper ratios (A4, A3, …, 1:√2):
:a_series(either orientation),:a_series_portrait,:a_series_landscape. A scan or export of an A4 page (595×842, 2480×3508) matches, with the same rounding and pixel of slack as custom ratios - custom aspect ratios (it must be of type
is_xx_yy)::is_16_9,:is_4_3, etc. A file matches a custom ratio when both ratios are equal once rounded to 3 decimals, or when one of its sides is within a pixel of the other one scaled to that ratio, so sizes such as 1366×768 (1366 × 9 / 16 = 768.375) match:is_16_9, while 1920×1082 does not. That pixel of slack only applies to images at least x×y pixels: a 4×3 or 1×1 image does not match:is_16_9.
- prebuilt aspect ratios:
Examples
Use it like this:
class User < ApplicationRecord
has_one_attached :avatar
has_one_attached :scan
validates :avatar, aspect_ratio: :square # restricts the aspect ratio to 1:1
validates :avatar, aspect_ratio: :portrait # restricts the aspect ratio to x:y where y > x
validates :avatar, aspect_ratio: :landscape # restricts the aspect ratio to x:y where x > y
validates :avatar, aspect_ratio: :is_16_9 # restricts the aspect ratio to 16:9
validates :avatar, aspect_ratio: %i[square is_16_9] # restricts the aspect ratio to 1:1 and 16:9
validates :scan, aspect_ratio: :a_series_portrait # restricts the aspect ratio to an upright A4 / A3 / … page
end
Error messages (I18n)
en:
errors:
messages:
aspect_ratio_not_square: "must be square (current file is %{width}x%{height}px)"
aspect_ratio_not_portrait: "must be portrait (current file is %{width}x%{height}px)"
aspect_ratio_not_landscape: "must be landscape (current file is %{width}x%{height}px)"
aspect_ratio_not_x_y: "must be %{authorized_aspect_ratios} (current file is %{width}x%{height}px)"
aspect_ratio_invalid: "has an invalid aspect ratio (valid aspect ratios are %{authorized_aspect_ratios})"
media_metadata_missing: "is not a valid media file"
attachment_missing: "is missing its attachment"
The A-series ratios use aspect_ratio_not_x_y.
The aspect_ratio validator error messages expose 4 values that you can use:
authorized_aspect_ratioscontaining the authorized aspect ratios, with the named ones in the current locale (e.g.square, 16:9,carré, 16:9in French)widthcontaining the current width of the image/videoheightcontaining the current height of the image/videofilenamecontaining the current filename in error
The names come from the active_storage_validations.aspect_ratios keys shipped with every bundled locale. Override them in your application locales like any other key:
en:
active_storage_validations:
aspect_ratios:
square: "square"
portrait: "portrait"
landscape: "landscape"
a_series: "A-series (1:√2)"
a_series_portrait: "A-series portrait (1:√2)"
a_series_landscape: "A-series landscape (√2:1)"
Processable file
Validates if the attached files can be processed by MiniMagick or Vips (image), ffmpeg (video/audio) or poppler (pdf). (be sure to have the right dependencies installed as mentioned in Getting started)
Options
The processable_file validator supports:
timeout: overrides the global analyzer command timeout for this validation
Examples
Use it like this:
class User < ApplicationRecord
has_one_attached :avatar
validates :avatar, processable_file: true # ensures that the file is processable by MiniMagick or Vips (image) or ffmpeg (video/audio)
validates :avatar, processable_file: { timeout: 5.seconds }
end
Notes
Rails 7.2.3.2+ / 8.0.5.1+ / 8.1.3.1+ call Vips.block_untrusted(true), so libvips refuses to load formats marked untrusted (e.g. SVG, BMP). Analysis then returns empty metadata by design. processable_file does not treat that as failure for those formats (BMP, ICO, PSD, SVG, JPEG XL, JPEG 2000, Netpbm), as long as the file's leading bytes are one of them: a file merely declared as image/bmp or image/svg+xml is still file_not_processable. dimension / aspect_ratio still need width/height — use MiniMagick for those formats, or skip those validators for them.
An empty but well-formed container (ffprobe exits 0 with no audio or video stream) is not processable. That is the same fail-closed miss as a corrupt file or a missing CLI.
An HLS / DASH playlist or an ffmpeg concat list (a text file naming other media files) is not processable, and has no dimension, duration or audio track, even when the files it names are valid: such files are recognized from their first bytes and never handed to ffprobe, which would open the files they name, on the server, and report their streams instead of the upload's.
libvips reads the image header only, while ImageMagick decodes the image. A truncated image whose header is intact is therefore processable with libvips, which also renders its variants (filling the missing rows), and not with ImageMagick.
Error messages (I18n)
en:
errors:
messages:
file_not_processable: "is not identified as a valid media file"
attachment_missing: "is missing its attachment"
The processable_file validator error messages expose 1 value that you can use:
filenamecontaining the current filename in error
Pages
Validates each attached pdf file number of pages. (be sure to have the right dependencies installed as mentioned in Using pdf metadata validators)
Options
The pages validator has several possible options:
less_than: defines the strict maximum allowed number of pagesless_than_or_equal_to: defines the maximum allowed number of pagesgreater_than: defines the strict minimum allowed number of pagesgreater_than_or_equal_to: defines the minimum allowed number of pagesbetween: defines the allowed number of pages rangeequal_to: defines the allowed number of pagestimeout: overrides the global analyzer command timeout for this validation
Pass one comparison option per validator (between covers a range); add a second validator to combine others.
Examples
Use it like this:
class User < ApplicationRecord
has_one_attached :contract
validates :contract, pages: { less_than: 2 } # restricts the number of pages to < 2
validates :contract, pages: { less_than_or_equal_to: 2 } # restricts the number of pages to <= 2
validates :contract, pages: { greater_than: 1 } # restricts the number of pages to > 1
validates :contract, pages: { greater_than_or_equal_to: 1 } # restricts the number of pages to >= 1
validates :contract, pages: { between: 1..2 } # restricts the number of pages to between 1 and 2
validates :contract, pages: { equal_to: 1 } # restricts the number of pages to exactly 1
end
Error messages (I18n)
en:
errors:
messages:
pages_not_less_than: "page count must be less than %{max} (current page count is %{pages})"
pages_not_less_than_or_equal_to: "page count must be less than or equal to %{max} (current page count is %{pages})"
pages_not_greater_than: "page count must be greater than %{min} (current page count is %{pages})"
pages_not_greater_than_or_equal_to: "page count must be greater than or equal to %{min} (current page count is %{pages})"
pages_not_between: "page count must be between %{min} and %{max} (current page count is %{pages})"
pages_not_equal_to: "page count must be equal to %{exact} (current page count is %{pages})"
media_metadata_missing: "is not a valid media file"
attachment_missing: "is missing its attachment"
media_metadata_missing is added when the file's page count cannot be read (not a PDF, missing pdfinfo, timed out analysis), and attachment_missing when the file of an attachment cannot be found on the storage service.
The pages validator error messages expose 5 values that you can use:
pagescontaining the current file number of pages (e.g.7)mincontaining the minimum allowed number of pages (e.g.1)exactcontaining the allowed number of pages (e.g.3)maxcontaining the maximum allowed number of pages (e.g.5; for exclusivebetween:ranges, the last included value)filenamecontaining the current file name
Upgrading
Internationalization (I18n)
Active Storage Validations uses I18n for error messages. The error messages are automatically loaded in your Rails app if your language translations are present in the gem.
Translation files are available here. We currently have translations for da, de, en, en-GB, es, fr, it, ja, nl, pl, pt-BR, ru, sv, tr, uk, vi and zh-CN. Feel free to drop a PR to add your language ✌️.
If you wish to customize the error messages, just copy, paste and update the translation files into your application locales.
Each validator section above lists the values its messages expose (%{min}, %{max}, %{filename}, …). A custom message: is shared by all the errors of its validator: a value an error does not carry is left blank, such as %{duration} when the file cannot be analyzed (media_metadata_missing). Those errors carry the bounds of duration, pages (%{min}, %{max}, %{exact}) and aspect_ratio (%{authorized_aspect_ratios}).
Test matchers
The gem also provides RSpec-compatible and Minitest-compatible matchers for testing the validators.
RSpec
Setup
In spec_helper.rb, you'll need to require the matchers:
require 'active_storage_validations/matchers'
And include the module:
RSpec.configure do |config|
config.include ActiveStorageValidations::Matchers
end
Matchers
Matcher methods available:
describe User do
# aspect_ratio:
# #allowing, #rejecting
it { is_expected.to validate_aspect_ratio_of(:avatar).allowing(:square, :portrait) } # possible to use an Array or *splatted array
it { is_expected.to validate_aspect_ratio_of(:avatar).rejecting(:square, :landscape) } # possible to use an Array or *splatted array
it { is_expected.to validate_aspect_ratio_of(:scan).allowing(:a_series_portrait) }
# attached
it { is_expected.to validate_attached_of(:avatar) }
# processable_file
it { is_expected.to validate_processable_file_of(:avatar) }
# limit
# #min, #max
it { is_expected.to validate_limits_of(:avatar).min(1) }
it { is_expected.to validate_limits_of(:avatar).max(5) }
# content_type:
# #allowing, #rejecting, #spoofing_protection
it { is_expected.to validate_content_type_of(:avatar).allowing('image/png', 'image/gif') } # possible to use an Array or *splatted array
it { is_expected.to validate_content_type_of(:avatar).rejecting('text/plain', 'text/xml') } # possible to use an Array or *splatted array
it { is_expected.to validate_content_type_of(:avatar).allowing('image/*').rejecting('video/*') } # every type Marcel knows of that media type
it { is_expected.to validate_content_type_of(:avatar).allowing('image/png').spoofing_protection } # true / :file
it { is_expected.to validate_content_type_of(:avatar).allowing('image/png').spoofing_protection(:magika) }
# dimension:
# #width, #height, #width_min, #height_min, #width_max, #height_max, #width_between, #height_between
it { is_expected.to validate_dimensions_of(:avatar).width(250) }
it { is_expected.to validate_dimensions_of(:avatar).height(200) }
it { is_expected.to validate_dimensions_of(:avatar).width_min(200) }
it { is_expected.to validate_dimensions_of(:avatar).height_min(100) }
it { is_expected.to validate_dimensions_of(:avatar).width_max(500) }
it { is_expected.to validate_dimensions_of(:avatar).height_max(300) }
it { is_expected.to validate_dimensions_of(:avatar).width_between(200..500) }
it { is_expected.to validate_dimensions_of(:avatar).width_between(200...500) } # exclusive end (200–499)
it { is_expected.to validate_dimensions_of(:avatar).height_between(100..300) }
# size:
# #less_than, #less_than_or_equal_to, #greater_than, #greater_than_or_equal_to, #between, #equal_to
it { is_expected.to validate_size_of(:avatar).less_than(50.kilobytes) }
it { is_expected.to validate_size_of(:avatar).less_than_or_equal_to(50.kilobytes) }
it { is_expected.to validate_size_of(:avatar).greater_than(1.kilobyte) }
it { is_expected.to validate_size_of(:avatar).greater_than_or_equal_to(1.kilobyte) }
it { is_expected.to validate_size_of(:avatar).between(100..500.kilobytes) }
it { is_expected.to validate_size_of(:avatar).equal_to(5.megabytes) }
# total_size (has_many_attached only):
# #less_than, #less_than_or_equal_to, #greater_than, #greater_than_or_equal_to, #between, #equal_to
it { is_expected.to validate_total_size_of(:certificates).less_than(50.kilobytes) }
it { is_expected.to validate_total_size_of(:certificates).less_than_or_equal_to(50.kilobytes) }
it { is_expected.to validate_total_size_of(:certificates).greater_than(1.kilobyte) }
it { is_expected.to validate_total_size_of(:certificates).greater_than_or_equal_to(1.kilobyte) }
it { is_expected.to validate_total_size_of(:certificates).between(100..500.kilobytes) }
it { is_expected.to validate_total_size_of(:certificates).equal_to(5.megabytes) }
# duration:
# #less_than, #less_than_or_equal_to, #greater_than, #greater_than_or_equal_to, #between, #equal_to
it { is_expected.to validate_duration_of(:introduction).less_than(50.seconds) }
it { is_expected.to validate_duration_of(:introduction).less_than_or_equal_to(50.seconds) }
it { is_expected.to validate_duration_of(:introduction).greater_than(1.minute) }
it { is_expected.to validate_duration_of(:introduction).greater_than_or_equal_to(1.minute) }
it { is_expected.to validate_duration_of(:introduction).between(100..500.seconds) }
it { is_expected.to validate_duration_of(:avatar).equal_to(5.minutes) }
it { is_expected.to validate_duration_of(:avatar).equal_to(5.seconds).precision(1) } # probes follow the validator's precision even without #precision
# with_audio
it { is_expected.to validate_with_audio_of(:video) }
it { is_expected.to validate_with_audio_of(:silent_video).without_audio }
it { is_expected.to validate_with_audio_of(:silent_video).without_audio.with_message("must not have an audio track") }
# pages:
# #less_than, #less_than_or_equal_to, #greater_than, #greater_than_or_equal_to, #between, #equal_to
it { is_expected.to validate_pages_of(:contract).less_than(50) }
it { is_expected.to validate_pages_of(:contract).less_than_or_equal_to(50) }
it { is_expected.to validate_pages_of(:contract).greater_than(5) }
it { is_expected.to validate_pages_of(:contract).greater_than_or_equal_to(5) }
it { is_expected.to validate_pages_of(:contract).between(100..500) }
it { is_expected.to validate_pages_of(:contract).equal_to(5) }
end
(Note that matcher methods are chainable)
All matchers can be customized with :on, :except_on and :message. All matchers except validate_attached_of support #allow_blank, and #timeout is available on the metadata matchers (aspect_ratio, dimension, duration, pages, processable_file, with_audio) and content_type:
describe User do
# :on
it { is_expected.to validate_attached_of(:avatar).on(:update) }
it { is_expected.to validate_attached_of(:avatar).on(%i[update custom]) }
# :except_on (Rails >= 8.0)
it { is_expected.to validate_attached_of(:avatar).except_on(:update) }
it { is_expected.to validate_attached_of(:avatar).except_on(%i[update custom]) }
# :message (the validator's `message:` option, or the message the error renders; a Regexp matches either)
it { is_expected.to validate_dimensions_of(:avatar).width(250).with_message('Invalid dimensions.') }
it { is_expected.to validate_size_of(:avatar).less_than(50.kilobytes).with_message(/must be less than 50 KB/) }
# :allow_blank (for a validator declared with `allow_blank: true`; not available on validate_attached_of)
it { is_expected.to validate_size_of(:avatar).less_than(50.kilobytes).allow_blank }
# :timeout (analyzer command timeout — metadata validators + content_type with spoofing)
it { is_expected.to validate_duration_of(:video).less_than(5.minutes).timeout(30.seconds) }
it { is_expected.to validate_with_audio_of(:video).timeout(5.seconds) }
it { is_expected.to validate_processable_file_of(:avatar).timeout(5.seconds) }
end
validate_limits_of(...).with_message(...) needs #min or #max to build a file count the validator rejects.
Matchers also work on validators declared with strict: true: their probes collect the errors instead of raising ActiveModel::StrictValidationFailed.
Minitest
Setup
To use the matchers, make sure you have the shoulda-context gem up and running. No extra mock library is required (minitest-mock is not needed on Minitest 6).
You need to require the matchers:
require 'active_storage_validations/matchers'
And extend the module:
class ActiveSupport::TestCase
extend ActiveStorageValidations::Matchers
end
Matchers
Then you can use the matchers with the syntax specified in the RSpec section, just use should validate_method instead of it { is_expected.to validate_method } as specified in the shoulda-context gem.
Contributing
If you want to contribute to the project, you will have to fork the repository and create a new branch from the master branch. Then build your feature, or fix the issue, and create a pull request. Be sure to add tests for your changes.
AI coding agents: see AGENTS.md for architecture, test commands, and contribution patterns. Commit and PR titles follow Conventional Commits.
Before submitting your pull request, run the tests to make sure everything works as expected.
To run the gem tests, launch the following commands in the root folder of gem repository:
BUNDLE_GEMFILE=gemfiles/rails_7_0_1.gemfile bundle exec rake specto run for Rails 7.0.1BUNDLE_GEMFILE=gemfiles/rails_7_1.gemfile bundle exec rake specto run for Rails 7.1BUNDLE_GEMFILE=gemfiles/rails_7_2.gemfile bundle exec rake specto run for Rails 7.2BUNDLE_GEMFILE=gemfiles/rails_8_0.gemfile bundle exec rake specto run for Rails 8.0BUNDLE_GEMFILE=gemfiles/rails_8_1.gemfile bundle exec rake specto run for Rails 8.1BUNDLE_GEMFILE=gemfiles/rails_next.gemfile bundle exec rake specto run for Rails main
Snippet to run in console:
BUNDLE_GEMFILE=gemfiles/rails_7_0_1.gemfile bundle
BUNDLE_GEMFILE=gemfiles/rails_7_1.gemfile bundle
BUNDLE_GEMFILE=gemfiles/rails_7_2.gemfile bundle
BUNDLE_GEMFILE=gemfiles/rails_8_0.gemfile bundle
BUNDLE_GEMFILE=gemfiles/rails_8_1.gemfile bundle
BUNDLE_GEMFILE=gemfiles/rails_next.gemfile bundle
BUNDLE_GEMFILE=gemfiles/rails_7_0_1.gemfile bundle exec rake spec
BUNDLE_GEMFILE=gemfiles/rails_7_1.gemfile bundle exec rake spec
BUNDLE_GEMFILE=gemfiles/rails_7_2.gemfile bundle exec rake spec
BUNDLE_GEMFILE=gemfiles/rails_8_0.gemfile bundle exec rake spec
BUNDLE_GEMFILE=gemfiles/rails_8_1.gemfile bundle exec rake spec
BUNDLE_GEMFILE=gemfiles/rails_next.gemfile bundle exec rake spec
Tips:
- To focus examples, tag them with
:focus(or usefit/fdescribe); RSpec is configured withfilter_run_when_matching :focus - To run a specific file:
bundle exec rspec spec/validators/size_validator_spec.rb - Image processor: CI runs both via
IMAGE_PROCESSOR=vips/IMAGE_PROCESSOR=mini_magick. Locally, unset means validators use MiniMagick (ASV default) and both analyzer unit specs run; setting the env selects that processor for validators and excludes the other processor’s tagged examples (so they do not show as pending)
Benchmarks
Optional wall-clock / ips suite for metadata validators (cold analysis vs cached asv_* hits) lives under benchmark/. See benchmark/README.md for setup, how to run, and how to refresh benchmark/BASELINE.md. CI runs the suite informationally (no fail-on-regression).
Additional information
Contributors (BIG THANK YOU!)
We have a long list of valued contributors. Check them all at:
https://github.com/igorkasyanchuk/active_storage_validations/graphs/contributors
License
The gem is available as open source under the terms of the MIT License.
Explore projetos relacionados
Carregando…
