Permalink
Browse files

Replace length of with numericality of

  • Loading branch information...
1 parent 5ce9ef2 commit 9abc6861f392638ff14ac1af2751cda082466f12 John Crepezzi committed Jan 21, 2011
Showing with 34 additions and 4 deletions.
  1. +3 −2 README.md
  2. +13 −1 lib/database_validation.rb
  3. +18 −1 spec/examples/validates_length_of_spec.rb
View
@@ -15,8 +15,9 @@ We need more tools that use tools we already have
For now:
* validates_uniquness_of (with scope)
-* validates_presence_of
-* validates_length_of :maximum
+* validates_presence_of
+* validates_length_of :maximum, :allow_nil
+* validates_numericality_of :greater_than, :less_than, :allow_nil
In the future:
View
@@ -14,8 +14,20 @@ def self.detect_validations(base)
base.columns.each do |field|
next if field.name == base.primary_key # don't add validations here
allow_nil = field.null
- base.send(:validates_length_of, field.name.to_sym, :maximum => field.limit, :allow_nil => allow_nil) unless field.limit.nil?
+
base.send(:validates_presence_of, field.name.to_sym, :allow_nil => allow_nil) unless allow_nil
+ next if field.limit.nil?
+
+ if [:integer, :float].include?(field.type)
+ unsigned = field.sql_type.include?('unsigned')
+ maximum = unsigned ? 2 ** (8 * field.limit) : 2 ** (8 * field.limit) / 2
+ minimum = unsigned ? -(2 ** (8 * field.limit)) - 1 : -(2 ** (8 * field.limit) / 2) - 1
+ base.send(:validates_numericality_of, field.name.to_sym, :less_than => maximum, :greater_than => minimum, :allow_nil => allow_nil)
+ else
+ maximum = field.limit
+ base.send(:validates_length_of, field.name.to_sym, :maximum => maximum, :allow_nil => allow_nil)
+ end
+
end
ActiveRecord::Base.connection.indexes(base.table_name).each do |key|
col_syms = key.columns.map(&:to_sym)
@@ -3,7 +3,7 @@
describe DatabaseValidation do
before(:all) do
- execute 'create table length1s (id int(11) auto_increment primary key, name varchar(10))'
+ execute 'create table length1s (id int(5) auto_increment primary key, name varchar(10), age smallint(1))'
execute 'create table length2s (id int(11) auto_increment primary key, body text)'
end
@@ -30,7 +30,24 @@ class Length2 < ActiveRecord::Base
include DatabaseValidation
end
end.should_not raise_error(ArgumentError)
+ end
+ it 'should properly validate length on integer fields' do
+ lambda do
+ Length1.create!(:age => 32769)
+ end.should raise_error(ActiveRecord::RecordInvalid)
+ lambda do
+ Length1.create!(:age => 32767)
+ end.should_not raise_error
+ end
+
+ it 'should properly validate length on integer fields minimum' do
+ lambda do
+ Length1.create!(:age => -32769)
+ end.should raise_error(ActiveRecord::RecordInvalid)
+ lambda do
+ Length1.create!(:age => -32768)
+ end.should_not raise_error
end
end

0 comments on commit 9abc686

Please sign in to comment.