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
  validat_mime_type_inclusion %w[image/jpeg image/png image/gif]
  validate_max_size 5*1024*1024 if record.guest?
end

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
end

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 [/\Aimage/], message: "is not an image"

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

Methods

Public Class

  1. configure

Constants

DEFAULT_MESSAGES = { max_size: ->(max) { "is larger than #{max.to_f/1024/1024} MB" }, min_size: ->(min) { "is smaller than #{min.to_f/1024/1024} MB" }, max_width: ->(max) { "is wider than #{max} px" }, min_width: ->(min) { "is narrower than #{min} px" }, max_height: ->(max) { "is taller than #{max} px" }, min_height: ->(min) { "is shorter than #{min} px" }, mime_type_inclusion: ->(list) { "isn't of allowed type: #{list.inspect}" }, mime_type_exclusion: ->(list) { "is of forbidden type: #{list.inspect}" }, extension_inclusion: ->(list) { "isn't in allowed format: #{list.inspect}" }, extension_exclusion: ->(list) { "is in forbidden format: #{list.inspect}" }, }  

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] || {})
end