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?
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 %w[image/jpeg image/png image/gif], message: "must be JPEG, PNG or GIF"

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

Methods

Public Class

  1. configure

Constants

DEFAULT_MESSAGES = { max_size: ->(max) { "is too large (max is #{PRETTY_FILESIZE.call(max)})" }, min_size: ->(min) { "is too small (min is #{PRETTY_FILESIZE.call(min)})" }, 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" }, }  
FILESIZE_UNITS = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"].freeze  
PRETTY_FILESIZE = lambda do |bytes| return "0.0 B" if bytes == 0 exp = Math.log(bytes, 1024).floor max_exp = FILESIZE_UNITS.length - 1 exp = max_exp if exp > max_exp "%.1f %s" % [bytes.to_f / 1024 ** exp, FILESIZE_UNITS[exp]] end  

Returns filesize in a human readable format with units. Uses the binary JEDEC unit system, i.e. 1.0 KB = 1024 bytes

Public Class methods

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