Skip to content

Commit

Permalink
only_integer of NumericalityValidator now allows procs and symbols
Browse files Browse the repository at this point in the history
  • Loading branch information
rmehner committed Jun 22, 2014
1 parent c2d5b31 commit 64a05a9
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
4 changes: 4 additions & 0 deletions activemodel/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
* 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
characters if validations are enabled.

Expand Down
14 changes: 13 additions & 1 deletion activemodel/lib/active_model/validations/numericality.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def validate_each(record, attr_name, value)
return
end

if options[:only_integer]
if allow_only_integer?(record)
unless value = parse_raw_value_as_an_integer(raw_value)
record.errors.add(attr_name, :not_an_integer, filtered_options(raw_value))
return
Expand Down Expand Up @@ -75,6 +75,17 @@ def filtered_options(value)
filtered[:value] = value
filtered
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

module HelperMethods
Expand Down Expand Up @@ -121,6 +132,7 @@ module HelperMethods
# * <tt>:equal_to</tt>
# * <tt>:less_than</tt>
# * <tt>:less_than_or_equal_to</tt>
# * <tt>:only_integer</tt>
#
# For example:
#
Expand Down
15 changes: 15 additions & 0 deletions activemodel/test/cases/validations/numericality_validation_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,21 @@ def test_validates_numericality_of_with_integer_only_and_nil_allowed
valid!(NIL + INTEGERS)
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
Topic.validates_numericality_of :approved, greater_than: 10

Expand Down

0 comments on commit 64a05a9

Please sign in to comment.