提交 6099b643 编写于 作者: R Rafael Mendonça França

Merge pull request #15834 from rmehner/allow_proc_and_symbol_for_only_integer

Allow proc and symbol as values for `only_integer` of `NumericalityValidator`
* Allow proc and symbol as values for `only_integer` of `NumericalityValidator`
*Robin Mehner*
* `has_secure_password` now verifies that the given password is less than 72 * `has_secure_password` now verifies that the given password is less than 72
characters if validations are enabled. characters if validations are enabled.
......
...@@ -30,7 +30,7 @@ def validate_each(record, attr_name, value) ...@@ -30,7 +30,7 @@ def validate_each(record, attr_name, value)
return return
end end
if options[:only_integer] if allow_only_integer?(record)
unless value = parse_raw_value_as_an_integer(raw_value) unless value = parse_raw_value_as_an_integer(raw_value)
record.errors.add(attr_name, :not_an_integer, filtered_options(raw_value)) record.errors.add(attr_name, :not_an_integer, filtered_options(raw_value))
return return
...@@ -75,6 +75,17 @@ def filtered_options(value) ...@@ -75,6 +75,17 @@ def filtered_options(value)
filtered[:value] = value filtered[:value] = value
filtered filtered
end end
def allow_only_integer?(record)
case options[:only_integer]
when Symbol
record.send(options[:only_integer])
when Proc
options[:only_integer].call(record)
else
options[:only_integer]
end
end
end end
module HelperMethods module HelperMethods
...@@ -121,6 +132,7 @@ module HelperMethods ...@@ -121,6 +132,7 @@ module HelperMethods
# * <tt>:equal_to</tt> # * <tt>:equal_to</tt>
# * <tt>:less_than</tt> # * <tt>:less_than</tt>
# * <tt>:less_than_or_equal_to</tt> # * <tt>:less_than_or_equal_to</tt>
# * <tt>:only_integer</tt>
# #
# For example: # For example:
# #
......
...@@ -50,6 +50,21 @@ def test_validates_numericality_of_with_integer_only_and_nil_allowed ...@@ -50,6 +50,21 @@ def test_validates_numericality_of_with_integer_only_and_nil_allowed
valid!(NIL + INTEGERS) valid!(NIL + INTEGERS)
end end
def test_validates_numericality_of_with_integer_only_and_symbol_as_value
Topic.validates_numericality_of :approved, only_integer: :condition_is_true_but_its_not
invalid!(NIL + BLANK + JUNK)
valid!(FLOATS + INTEGERS + BIGDECIMAL + INFINITY)
end
def test_validates_numericality_of_with_integer_only_and_proc_as_value
Topic.send(:define_method, :allow_only_integers?, lambda { false })
Topic.validates_numericality_of :approved, only_integer: Proc.new {|topic| topic.allow_only_integers? }
invalid!(NIL + BLANK + JUNK)
valid!(FLOATS + INTEGERS + BIGDECIMAL + INFINITY)
end
def test_validates_numericality_with_greater_than def test_validates_numericality_with_greater_than
Topic.validates_numericality_of :approved, greater_than: 10 Topic.validates_numericality_of :approved, greater_than: 10
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册