Module: Shrine::Plugins::ValidationHelpers

Defined in:
lib/shrine/plugins/validation_helpers.rb

Overview

Documentation can be found on shrinerb.com/docs/plugins/validation_helpers

Defined Under Namespace

Modules: AttacherClassMethods, AttacherMethods

Constant Summary collapse

DEFAULT_MESSAGES =
{
  max_size:            -> (max)  { "size must not be greater than #{PRETTY_FILESIZE.call(max)}" },
  min_size:            -> (min)  { "size must not be less than #{PRETTY_FILESIZE.call(min)}" },
  max_width:           -> (max)  { "width must not be greater than #{max}px" },
  min_width:           -> (min)  { "width must not be less than #{min}px" },
  max_height:          -> (max)  { "height must not be greater than #{max}px" },
  min_height:          -> (min)  { "height must not be less than #{min}px" },
  max_dimensions:      -> (dims) { "dimensions must not be greater than #{dims.join("x")}" },
  min_dimensions:      -> (dims) { "dimensions must not be less than #{dims.join("x")}" },
  mime_type_inclusion: -> (list) { "type must be one of: #{list.join(", ")}" },
  mime_type_exclusion: -> (list) { "type must not be one of: #{list.join(", ")}" },
  extension_inclusion: -> (list) { "extension must be one of: #{list.join(", ")}" },
  extension_exclusion: -> (list) { "extension must not be one of: #{list.join(", ")}" },
}.freeze
FILESIZE_UNITS =
["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"].freeze
PRETTY_FILESIZE =

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

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

Class Method Summary collapse

Class Method Details

.configure(uploader, default_messages: {}, **opts) ⇒ Object


39
40
41
42
# File 'lib/shrine/plugins/validation_helpers.rb', line 39

def self.configure(uploader, default_messages: {}, **opts)
  uploader.opts[:validation_helpers] ||= { default_messages: DEFAULT_MESSAGES.dup }
  uploader.opts[:validation_helpers][:default_messages].merge!(default_messages)
end

.load_dependencies(uploader) ⇒ Object


35
36
37
# File 'lib/shrine/plugins/validation_helpers.rb', line 35

def self.load_dependencies(uploader, *)
  uploader.plugin :validation
end