Skip to content

Instantly share code, notes, and snippets.

@dtaniwaki
Created March 14, 2014 07:16
Show Gist options
  • Save dtaniwaki/9543340 to your computer and use it in GitHub Desktop.
Save dtaniwaki/9543340 to your computer and use it in GitHub Desktop.
class ByteSizeValidator < ActiveModel::Validations::LengthValidator
def validate_each(record, attribute, value)
value_length = value.respond_to?(:bytesize) ? value.bytesize : value.to_s.bytesize
CHECKS.each do |key, validity_check|
next unless check_value = options[key]
next if value_length.send(validity_check, check_value)
errors_options = options.except(*RESERVED_OPTIONS)
errors_options[:count] = check_value
default_message = options[MESSAGES[key]]
errors_options[:message] ||= default_message if default_message
record.errors.add(attribute, MESSAGES[key], errors_options)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment