module Shrine::Plugins::ValidationHelpers

  1. lib/shrine/plugins/validation_helpers.rb

The validation_helpers plugin provides helper methods for validating attached files.

plugin :validation_helpers

Attacher.validate do
  validate_mime_type_inclusion %w[image/jpeg image/png image/gif]
  validate_max_size 5*1024*1024 if record.guest?

The validation methods are instance-level, the Attacher.validate block is evaluated in context of an instance of Shrine::Attacher, so you can easily do conditional validation.

The validation methods return whether the validation succeeded, allowing you to do conditional validation.

if validate_mime_type_inclusion %w[image/jpeg image/png image/gif]
  validate_max_width 2000
  validate_max_height 2000

If you would like to change default validation error messages, you can pass in the :default_messages option to the plugin:

plugin :validation_helpers, default_messages: {
  max_size: ->(max) { I18n.t("errors.file.max_size", max: max) },
  mime_type_inclusion: ->(whitelist) { I18n.t("errors.file.mime_type_inclusion", whitelist: whitelist) },

If you would like to change the error message inline, you can pass the :message option to any validation method:

validate_mime_type_inclusion %w[image/jpeg image/png image/gif], message: "must be JPEG, PNG or GIF"

For a complete list of all validation helpers, see AttacherMethods.


Public Class

  1. configure


DEFAULT_MESSAGES = { max_size: ->(max) { "is too large (max is #{max.to_f/1024/1024} MB)" }, min_size: ->(min) { "is too small (min is #{min.to_f/1024/1024} MB)" }, max_width: ->(max) { "is too wide (max is #{max} px)" }, min_width: ->(min) { "is too narrow (min is #{min} px)" }, max_height: ->(max) { "is too tall (max is #{max} px)" }, min_height: ->(min) { "is too short (min is #{min} px)" }, mime_type_inclusion: ->(list) { "isn't of allowed type (allowed types: #{list.join(", ")})" }, mime_type_exclusion: ->(list) { "is of forbidden type" }, extension_inclusion: ->(list) { "isn't of allowed format (allowed formats: #{list.join(", ")})" }, extension_exclusion: ->(list) { "is of forbidden format" }, }  

Public Class methods

configure (uploader, opts = {})
[show source]
# File lib/shrine/plugins/validation_helpers.rb, line 40
def self.configure(uploader, opts = {})
  uploader.opts[:validation_default_messages] = (uploader.opts[:validation_default_messages] || {}).merge(opts[:default_messages] || {})