debian-mirror-gitlab/lib/file_size_validator.rb

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

78 lines
2.3 KiB
Ruby
Raw Normal View History

2018-12-13 13:39:08 +05:30
# frozen_string_literal: true
2014-09-02 18:07:02 +05:30
class FileSizeValidator < ActiveModel::EachValidator
2016-06-02 11:05:42 +05:30
MESSAGES = { is: :wrong_size, minimum: :size_too_small, maximum: :size_too_big }.freeze
CHECKS = { is: :==, minimum: :>=, maximum: :<= }.freeze
2014-09-02 18:07:02 +05:30
2023-06-09 08:11:10 +05:30
DEFAULT_TOKENIZER = -> (value) { value.split("") }.freeze
2016-06-02 11:05:42 +05:30
RESERVED_OPTIONS = [:minimum, :maximum, :within, :is, :tokenizer, :too_short, :too_long].freeze
2014-09-02 18:07:02 +05:30
def initialize(options)
if range = (options.delete(:in) || options.delete(:within))
raise ArgumentError, ":in and :within must be a Range" unless range.is_a?(Range)
2018-03-17 18:26:18 +05:30
2021-04-29 21:17:54 +05:30
options[:minimum] = range.begin
options[:maximum] = range.end
2014-09-02 18:07:02 +05:30
options[:maximum] -= 1 if range.exclude_end?
end
super
end
def check_validity!
keys = CHECKS.keys & options.keys
if keys.empty?
raise ArgumentError, 'Range unspecified. Specify the :within, :maximum, :minimum, or :is option.'
end
keys.each do |key|
value = options[key]
2015-04-26 12:48:37 +05:30
unless (value.is_a?(Integer) && value >= 0) || value.is_a?(Symbol)
raise ArgumentError, ":#{key} must be a nonnegative Integer or symbol"
2014-09-02 18:07:02 +05:30
end
end
end
def validate_each(record, attribute, value)
2017-08-17 22:00:37 +05:30
raise(ArgumentError, "A CarrierWave::Uploader::Base object was expected") unless value.is_a? CarrierWave::Uploader::Base
2014-09-02 18:07:02 +05:30
2017-08-17 22:00:37 +05:30
value = (options[:tokenizer] || DEFAULT_TOKENIZER).call(value) if value.is_a?(String)
2014-09-02 18:07:02 +05:30
CHECKS.each do |key, validity_check|
next unless check_value = options[key]
2015-04-26 12:48:37 +05:30
check_value =
case check_value
when Integer
check_value
when Symbol
2018-03-17 18:26:18 +05:30
record.public_send(check_value) # rubocop:disable GitlabSecurity/PublicSend
2015-04-26 12:48:37 +05:30
end
2014-09-02 18:07:02 +05:30
value ||= [] if key == :maximum
value_size = value.size
2018-03-17 18:26:18 +05:30
next if value_size.public_send(validity_check, check_value) # rubocop:disable GitlabSecurity/PublicSend
2014-09-02 18:07:02 +05:30
errors_options = options.except(*RESERVED_OPTIONS)
errors_options[:file_size] = help.number_to_human_size check_value
default_message = options[MESSAGES[key]]
errors_options[:message] ||= default_message if default_message
2021-06-08 01:23:25 +05:30
record.errors.add(attribute, MESSAGES[key], **errors_options)
2014-09-02 18:07:02 +05:30
end
end
def help
Helper.instance
end
class Helper
include Singleton
include ActionView::Helpers::NumberHelper
end
end