diff options
Diffstat (limited to 'activerecord/lib/active_record/type/numeric.rb')
-rw-r--r-- | activerecord/lib/active_record/type/numeric.rb | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/activerecord/lib/active_record/type/numeric.rb b/activerecord/lib/active_record/type/numeric.rb new file mode 100644 index 0000000000..137c9e4c99 --- /dev/null +++ b/activerecord/lib/active_record/type/numeric.rb @@ -0,0 +1,42 @@ +module ActiveRecord + module Type + module Numeric # :nodoc: + def number? + true + end + + def type_cast(value) + value = case value + when true then 1 + when false then 0 + when ::String then value.presence + else value + end + super(value) + 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 + end + + private + + 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 + end + end + end +end |