diff options
Diffstat (limited to 'activemodel/lib/active_model/validations/numericality.rb')
-rw-r--r-- | activemodel/lib/active_model/validations/numericality.rb | 29 |
1 files changed, 17 insertions, 12 deletions
diff --git a/activemodel/lib/active_model/validations/numericality.rb b/activemodel/lib/active_model/validations/numericality.rb index 48e0e5c9f6..0478915be7 100644 --- a/activemodel/lib/active_model/validations/numericality.rb +++ b/activemodel/lib/active_model/validations/numericality.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module ActiveModel module Validations class NumericalityValidator < EachValidator # :nodoc: @@ -17,9 +19,11 @@ module ActiveModel end def validate_each(record, attr_name, value) - before_type_cast = :"#{attr_name}_before_type_cast" + came_from_user = :"#{attr_name}_came_from_user?" - raw_value = record.send(before_type_cast) if record.respond_to?(before_type_cast) && record.send(before_type_cast) != value + if record.respond_to?(came_from_user) && record.public_send(came_from_user) + raw_value = record.read_attribute_before_type_cast(attr_name) + end raw_value ||= value if record_attribute_changed_in_place?(record, attr_name) @@ -36,7 +40,9 @@ module ActiveModel return end - unless raw_value.is_a?(Numeric) + if raw_value.is_a?(Numeric) + value = raw_value + else value = parse_raw_value_as_a_number(raw_value) end @@ -61,7 +67,7 @@ module ActiveModel end end - protected + private def is_number?(raw_value) !parse_raw_value_as_a_number(raw_value).nil? @@ -70,6 +76,7 @@ module ActiveModel end def parse_raw_value_as_a_number(raw_value) + return raw_value.to_i if is_integer?(raw_value) Kernel.Float(raw_value) if raw_value !~ /\A0[xX]/ end @@ -94,18 +101,16 @@ module ActiveModel end end - private - - def record_attribute_changed_in_place?(record, attr_name) - record.respond_to?(:attribute_changed_in_place?) && - record.attribute_changed_in_place?(attr_name.to_s) - end + def record_attribute_changed_in_place?(record, attr_name) + record.respond_to?(:attribute_changed_in_place?) && + record.attribute_changed_in_place?(attr_name.to_s) + end end module HelperMethods # Validates whether the value of the specified attribute is numeric by # trying to convert it to a float with Kernel.Float (if <tt>only_integer</tt> - # is +false+) or applying it to the regular expression <tt>/\A[\+\-]?\d+\Z/</tt> + # is +false+) or applying it to the regular expression <tt>/\A[\+\-]?\d+\z/</tt> # (if <tt>only_integer</tt> is set to +true+). # # class Person < ActiveRecord::Base @@ -136,7 +141,7 @@ module ActiveModel # # There is also a list of default options supported by every validator: # +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+ . - # See <tt>ActiveModel::Validation#validates</tt> for more information + # See <tt>ActiveModel::Validations#validates</tt> for more information # # The following checks can also be supplied with a proc or a symbol which # corresponds to a method: |