| Module | ActiveRecord::Validations::ClassMethods |
| In: |
lib/rails/active_record_ext.rb
|
Exactly like rails 2.0.2, except too_short, to_long translated
# File lib/rails/active_record_ext.rb, line 65
65: def validates_length_of(*attrs)
66: # Merge given options with defaults.
67: options = {
68: :too_long => ActiveRecord::Errors.default_error_messages[:too_long],
69: :too_short => ActiveRecord::Errors.default_error_messages[:too_short],
70: :wrong_length => ActiveRecord::Errors.default_error_messages[:wrong_length]
71: }.merge(DEFAULT_VALIDATION_OPTIONS)
72: options.update(attrs.extract_options!.symbolize_keys)
73:
74: # Ensure that one and only one range option is specified.
75: range_options = ALL_RANGE_OPTIONS & options.keys
76: case range_options.size
77: when 0
78: raise ArgumentError, 'Range unspecified. Specify the :within, :maximum, :minimum, or :is option.'
79: when 1
80: # Valid number of options; do nothing.
81: else
82: raise ArgumentError, 'Too many range options specified. Choose only one.'
83: end
84:
85: # Get range option and value.
86: option = range_options.first
87: option_value = options[range_options.first]
88:
89: myfirst = true
90:
91: case option
92: when :within, :in
93: raise ArgumentError, ":#{option} must be a Range" unless option_value.is_a?(Range)
94:
95: validates_each(attrs, options) do |record, attr, value|
96:
97: if myfirst == true
98: myfirst = false
99: too_short = options[:too_short][options[:too_short].tr('[ ]', '_').to_sym] % option_value.begin
100: too_long = options[:too_long][options[:too_long].tr('[ ]', '_').to_sym] % option_value.end
101: end
102:
103: if value.nil? or value.split(//).size < option_value.begin
104: record.errors.add(attr, too_short)
105: elsif value.split(//).size > option_value.end
106: record.errors.add(attr, too_long)
107: end
108: end
109: when :is, :minimum, :maximum
110: raise ArgumentError, ":#{option} must be a nonnegative Integer" unless option_value.is_a?(Integer) and option_value >= 0
111:
112: # Declare different validations per option.
113: validity_checks = { :is => "==", :minimum => ">=", :maximum => "<=" }
114: message_options = { :is => :wrong_length, :minimum => :too_short, :maximum => :too_long }
115:
116: message = (options[:message] || options[message_options[option]]) % option_value
117:
118: validates_each(attrs, options) do |record, attr, value|
119: if value.kind_of?(String)
120: record.errors.add(attr, message) unless !value.nil? and value.split(//).size.method(validity_checks[option])[option_value]
121: else
122: record.errors.add(attr, message) unless !value.nil? and value.size.method(validity_checks[option])[option_value]
123: end
124: end
125: end
126: end