Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
A

active_storage_validations

> 后端框架
Open source

Do it like => validates :photos, attached: true, content_type: ['image/png', 'image/jpg', 'image/jpeg'], size: { less_than: 500.kilobytes }, limit: { min: 1, ma

1.2K stars0 likes5 views
WebsiteGitHub

About

Do it like => validates :photos, attached: true, content_type: ['image/png', 'image/jpg', 'image/jpeg'], size: { less_than: 500.kilobytes }, limit: { min: 1, ma

Active 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
    • Installation
    • Error messages (I18n)
    • Using image metadata validators
    • Using video and audio metadata validators
    • Using pdf metadata validators
    • Using content type spoofing protection validator option
    • Configuration
  • Validators
    • Attached
    • Limit
    • Content type
    • Size
    • Total size
    • Dimension
    • Duration
    • With audio
    • Aspect ratio
    • Processable file
    • Pages
  • 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:

ruby
gem 'active_storage_validations'

And then execute:

bash
$ 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:

ruby
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× faster than MiniMagick/ImageMagick on the same machine and fixtures. 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 UNIX file command (usually preinstalled on UNIX systems)
  • Magika backend (:magika): the Google Magika CLI — install via brew install magika, their install script, cargo install --locked magika-cli, or pipx 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:

…

The gem emits two ActiveSupport::Notifications events:

Event Payload Emitted
analyze.active_storage_validations analyzer, command, timeout, timed_out, duration Every time an analyzer command runs (i.e. on a cache miss)
timeout.active_storage_validations analyzer, command, timeout Only when a command exceeds its deadline

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 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):

ruby
validates :video, duration: { less_than: 5.minutes, timeout: 30.seconds }

Notes:

  • Setting command_timeout (or per-validator timeout:) to nil disables the deadline
  • ImageMagick analysis runs identify through 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

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

Proc usage

Every validator can use procs instead of values in all the validator examples:

ruby
class User  (record) { record.admin? ? 100 : 10 } }
end

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.


Attached

Validates if the attachment is present.

Options

The attached validator has no options.

Examples

Use it like this:

ruby
class User 
  
    %>

Explicit accept values are never overridden. You can also disable inference:

erb
ruby
# 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:

  • Only broad MIME-type regexes of the form /\Aimage\/.*\z/ (or video / audio / etc.) are inferred, as image/*
  • Other regexes (e.g. /\Aimage\/(png|gif)\z/) are skipped, since they cannot be reliably represented in accept
  • Proc / dynamic content_type options are skipped: 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 custom accept: on those fields if you want the picker filtered
  • Conditional validators (if: / unless:) are not evaluated: their content types are always included in accept, even when the condition would skip the validator for that record. Backend validation is unchanged; use infer_accept: false (or a custom accept:) 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. On Marcel 2 (Rails 8.2+), historical aliases such as audio/x-aac are still valid options and resolve to their canonical type (audio/aac). If the type is not registered, you can register it by adding the following code to your config/initializers/mime_types.rb file:

ruby
Marcel::MimeType.extend "application/ino", extensions: %w(ino), parents: "text/plain" # Registering arduino INO files

Be sure to at least include one the extensions, parents or magic option, 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:

ruby
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) — UNIX file / libmagic, mostly magic

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubyactive-storageactivestoragerailsvalidations

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架