1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Raise a descriptive error if non-positive integer passed to in_groups_of.

This is more consistent than the current behaviour of raising a
`ZeroDivisionError: divided by 0` error when 0 is given, which can be
non-obvious especially if `in_groups_of` is part of a longer chain of
methods.

The negative case was ok - "ArgumentError: invalid slice size" - but
this error is clearer still.
This commit is contained in:
Xavier Shay 2014-07-30 20:00:31 -07:00
parent 29a6a17a11
commit acac631cc9
2 changed files with 11 additions and 0 deletions

View file

@ -18,6 +18,11 @@ class Array
# ["3", "4"]
# ["5"]
def in_groups_of(number, fill_with = nil)
if number.to_i <= 0
raise ArgumentError,
"Group size must be a positive integer, was #{number.inspect}"
end
if fill_with == false
collection = self
else

View file

@ -90,6 +90,12 @@ class GroupingTest < ActiveSupport::TestCase
assert_equal [[1, 2, 3], [4, 5], [6, 7]],
(1..7).to_a.in_groups(3, false)
end
def test_in_groups_invalid_argument
assert_raises(ArgumentError) { [].in_groups_of(0) }
assert_raises(ArgumentError) { [].in_groups_of(-1) }
assert_raises(ArgumentError) { [].in_groups_of(nil) }
end
end
class SplitTest < ActiveSupport::TestCase