File: bytesize_validator.rb

package info (click to toggle)
gitlab 17.6.5-19
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 629,368 kB
  • sloc: ruby: 1,915,304; javascript: 557,307; sql: 60,639; xml: 6,509; sh: 4,567; makefile: 1,239; python: 406
file content (30 lines) | stat: -rw-r--r-- 1,023 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# frozen_string_literal: true

# BytesizeValidator
#
# Custom validator for verifying that bytesize of a field doesn't exceed the specified limit.
# It is different from Rails length validator because it takes .bytesize into account instead of .size/.length
#
# Example:
#
#   class Snippet < ActiveRecord::Base
#     validates :content, bytesize: { maximum: -> { Gitlab::CurrentSettings.snippet_size_limit } }
#   end
#
# Configuration options:
# * <tt>maximum</tt> - Proc that evaluates the bytesize limit that cannot be exceeded
class BytesizeValidator < ActiveModel::EachValidator
  def validate_each(record, attr, value)
    size = value.to_s.bytesize
    max_size = options[:maximum].call

    return if size <= max_size

    error_message = format(_('is too long (%{size}). The maximum size is %{max_size}.'), {
      size: ActiveSupport::NumberHelper.number_to_human_size(size),
      max_size: ActiveSupport::NumberHelper.number_to_human_size(max_size)
    })

    record.errors.add(attr, error_message)
  end
end