Methods
- C
- N
- V
Constants
MESSAGES | = | { :is => :wrong_length, :minimum => :too_short, :maximum => :too_long }.freeze |
CHECKS | = | { :is => :==, :minimum => :>=, :maximum => :<= }.freeze |
RESERVED_OPTIONS | = | [:minimum, :maximum, :within, :is, :tokenizer, :too_short, :too_long] |
Class Public methods
# File activemodel/lib/active_model/validations/length.rb, line 12 12: def initialize(options) 13: if range = (options.delete(:in) || options.delete(:within)) 14: raise ArgumentError, ":in and :within must be a Range" unless range.is_a?(Range) 15: options[:minimum], options[:maximum] = range.begin, range.end 16: options[:maximum] -= 1 if range.exclude_end? 17: end 18: 19: super 20: end
Instance Public methods
# File activemodel/lib/active_model/validations/length.rb, line 22 22: def check_validity! 23: keys = CHECKS.keys & options.keys 24: 25: if keys.empty? 26: raise ArgumentError, 'Range unspecified. Specify the :in, :within, :maximum, :minimum, or :is option.' 27: end 28: 29: keys.each do |key| 30: value = options[key] 31: 32: unless value.is_a?(Integer) && value >= 0 33: raise ArgumentError, ":#{key} must be a nonnegative Integer" 34: end 35: end 36: end
# File activemodel/lib/active_model/validations/length.rb, line 38 38: def validate_each(record, attribute, value) 39: value = tokenize(value) 40: value_length = value.respond_to?(:length) ? value.length : value.to_s.length 41: 42: CHECKS.each do |key, validity_check| 43: next unless check_value = options[key] 44: next if value_length.send(validity_check, check_value) 45: 46: errors_options = options.except(*RESERVED_OPTIONS) 47: errors_options[:count] = check_value 48: 49: default_message = options[MESSAGES[key]] 50: errors_options[:message] ||= default_message if default_message 51: 52: record.errors.add(attribute, MESSAGES[key], errors_options) 53: end 54: end