11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
# File 'lib/validates_lengths_from_database.rb', line 11
def validates_lengths_from_database(options = {})
return unless self.table_exists? options.symbolize_keys!
raise ArgumentError, "The :only option to validates_lengths_from_database must be an array." if options[:only] and !options[:only].is_a?(Array)
raise ArgumentError, "The :except option to validates_lengths_from_database must be an array." if options[:except] and !options[:except].is_a?(Array)
if options[:only]
columns_to_validate = options[:only].map(&:to_s)
else
columns_to_validate = column_names.map(&:to_s)
columns_to_validate -= options[:except].map(&:to_s) if options[:except]
end
columns_to_validate.each do |column|
column_schema = columns.find {|c| c.name == column }
next if column_schema.nil?
next if ![:string, :text].include?(column_schema.type)
next if column_schema.limit.nil?
class_eval do
validates_length_of column, :maximum => column_schema.limit, :allow_blank => true
end
end
nil
end
|