blob: 137c9e4c99961dc93fab2c3963ca645e25276ccc (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
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
38
39
40
41
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
|