Sha256: 08d95071961b1d09c5a75b6a8f3a98c258530c7113d62f9935850305a2b11e0e
Contents?: true
Size: 1.3 KB
Versions: 7
Compression:
Stored size: 1.3 KB
Contents
module ActiveModel module Validations class BytesizeValidator < ActiveModel::EachValidator attr_reader :encoding def initialize(options = {}) super @encoding = Encoding.find(options[:encoding]) if options[:encoding] end def check_validity! unless options[:maximum].is_a?(Integer) && options[:maximum] >= 0 raise ArgumentError, ":maximum must be set to a nonnegative Integer" end end def validate_each(record, attribute, value) string = value.to_s string = string.encode(options[:encoding]) if requires_transcoding?(string) if string.bytesize > options[:maximum] errors_options = options.except(:too_many_bytes, :maximum) default_message = options[:too_many_bytes] errors_options[:count] = options[:maximum] errors_options[:message] ||= default_message if default_message record.errors.add(attribute, :too_many_bytes, errors_options) end end def requires_transcoding?(value) encoding.present? && encoding != value.encoding end end module HelperMethods def validates_bytesize_of(*attr_names) validates_with ActiveModel::Validations::BytesizeValidator, _merge_attributes(attr_names) end end end end
Version data entries
7 entries across 7 versions & 1 rubygems