diff options
author | Sean Griffin <sean@thoughtbot.com> | 2014-06-19 09:47:40 -0600 |
---|---|---|
committer | Sean Griffin <sean@thoughtbot.com> | 2014-06-19 09:47:40 -0600 |
commit | 0aecb473c34b5df3b020ef4ede6d8e36f9009fd7 (patch) | |
tree | baf8e48d01133f94b9299a83bb2f4a47acc3f8a4 /activerecord | |
parent | dccf6da66bf4a63971e1f12b98cb1bb1fe5a9015 (diff) | |
download | rails-0aecb473c34b5df3b020ef4ede6d8e36f9009fd7.tar.gz rails-0aecb473c34b5df3b020ef4ede6d8e36f9009fd7.tar.bz2 rails-0aecb473c34b5df3b020ef4ede6d8e36f9009fd7.zip |
Further simplify `changed?` conditional for numeric types
`Type::Integer.new.type_cast('') # => nil`, we do not need a special
case to handle this, `nil => ''` already returns false. The only case we
need to handle is `0 => 'wibble'` should be changed, while `0 => '0'`
should not.
Diffstat (limited to 'activerecord')
-rw-r--r-- | activerecord/lib/active_record/type/numeric.rb | 18 |
1 files changed, 6 insertions, 12 deletions
diff --git a/activerecord/lib/active_record/type/numeric.rb b/activerecord/lib/active_record/type/numeric.rb index 137c9e4c99..a7bf0657b9 100644 --- a/activerecord/lib/active_record/type/numeric.rb +++ b/activerecord/lib/active_record/type/numeric.rb @@ -16,26 +16,20 @@ module ActiveRecord end def changed?(old_value, _new_value, new_value_before_type_cast) # :nodoc: - # 0 => 'wibble' should mark as changed so numericality validations run - if nil_or_zero?(old_value) && non_numeric_string?(new_value_before_type_cast) - # nil => '' should not mark as changed - old_value != new_value_before_type_cast.presence - else - super - end + super || zero_to_non_number?(old_value, new_value_before_type_cast) end private + def zero_to_non_number?(old_value, new_value_before_type_cast) + old_value == 0 && non_numeric_string?(new_value_before_type_cast) + end + def non_numeric_string?(value) # 'wibble'.to_i will give zero, we want to make sure # that we aren't marking int zero to string zero as # changed. - value !~ /\A\d+\.?\d*\z/ - end - - def nil_or_zero?(value) - value.nil? || value == 0 + value.to_s !~ /\A\d+\.?\d*\z/ end end end |