Merge pull request #35010 from Edouard-chin/ec-numericality-validator-fix

Fix NumericalityValidator on object responding to `to_f`:
This commit is contained in:
Rafael França 2019-01-22 15:33:54 -05:00 committed by GitHub
commit ea6a488f51
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 8 deletions

View File

@ -10,7 +10,6 @@ module ActiveModel
RESERVED_OPTIONS = CHECKS.keys + [:only_integer]
INTEGER_REGEX = /\A[+-]?\d+\z/
DECIMAL_REGEX = /\A[+-]?\d+\.?\d*(e|e[+-])?\d+\z/
def check_validity!
keys = CHECKS.keys - [:odd, :even]
@ -92,8 +91,8 @@ module ActiveModel
raw_value
elsif is_integer?(raw_value)
raw_value.to_i
elsif is_decimal?(raw_value) && !is_hexadecimal_literal?(raw_value)
BigDecimal(raw_value)
elsif !is_hexadecimal_literal?(raw_value)
Kernel.Float(raw_value).to_d
end
end
@ -101,12 +100,8 @@ module ActiveModel
INTEGER_REGEX.match?(raw_value.to_s)
end
def is_decimal?(raw_value)
DECIMAL_REGEX.match?(raw_value.to_s)
end
def is_hexadecimal_literal?(raw_value)
/\A0[xX]/.match?(raw_value)
/\A0[xX]/.match?(raw_value.to_s)
end
def filtered_options(value)

View File

@ -281,6 +281,19 @@ class NumericalityValidationTest < ActiveModel::TestCase
assert_predicate topic, :invalid?
end
def test_validates_numericalty_with_object_acting_as_numeric
klass = Class.new do
def to_f
123.54
end
end
Topic.validates_numericality_of :price
topic = Topic.new(price: klass.new)
assert_predicate topic, :valid?
end
def test_validates_numericality_with_invalid_args
assert_raise(ArgumentError) { Topic.validates_numericality_of :approved, greater_than_or_equal_to: "foo" }
assert_raise(ArgumentError) { Topic.validates_numericality_of :approved, less_than_or_equal_to: "foo" }