Skip to content

Commit

Permalink
Ignore non-integer ranges in Style/RandomWithOffset
Browse files Browse the repository at this point in the history
This cop only works correctly for ranges with integer bounds.
  • Loading branch information
eugeneius authored and marcandre committed Sep 21, 2020
1 parent 4d6e725 commit 058d541
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -12,6 +12,7 @@
* [#8739](https://github.com/rubocop-hq/rubocop/issues/8739): Fix an error for `Lint/UselessTimes` when using empty block argument. ([@koic][])
* [#8742](https://github.com/rubocop-hq/rubocop/issues/8742): Fix some assignment counts for `Metrics/AbcSize`. ([@marcandre][])
* [#8750](https://github.com/rubocop-hq/rubocop/pull/8750): Fix an incorrect auto-correct for `Style/MultilineWhenThen` when line break for multiple condidate values of `when` statement. ([@koic][])
* [#8754](https://github.com/rubocop-hq/rubocop/pull/8754): Fix an error for `Style/RandomWithOffset` when using a range with non-integer bounds. ([@eugeneius][])

### Changes

Expand Down
6 changes: 3 additions & 3 deletions lib/rubocop/cop/style/random_with_offset.rb
Expand Up @@ -36,15 +36,15 @@ class RandomWithOffset < Base
(send
{nil? (const {nil? cbase} :Random) (const {nil? cbase} :Kernel)}
:rand
{int irange erange}))
{int (irange int int) (erange int int)}))
PATTERN

def_node_matcher :rand_op_integer?, <<~PATTERN
(send
(send
{nil? (const {nil? cbase} :Random) (const {nil? cbase} :Kernel)}
:rand
{int irange erange})
{int (irange int int) (erange int int)})
{:+ :-}
int)
PATTERN
Expand All @@ -54,7 +54,7 @@ class RandomWithOffset < Base
(send
{nil? (const {nil? cbase} :Random) (const {nil? cbase} :Kernel)}
:rand
{int irange erange})
{int (irange int int) (erange int int)})
{:succ :pred :next})
PATTERN

Expand Down
24 changes: 24 additions & 0 deletions spec/rubocop/cop/style/random_with_offset_spec.rb
Expand Up @@ -258,6 +258,30 @@
RUBY
end

it 'does not register an offense when using rand(irange) + offset with a non-integer range value' do
expect_no_offenses(<<~RUBY)
rand(0..limit) + 1
RUBY
end

it 'does not register an offense when using offset - rand(erange) with a non-integer range value' do
expect_no_offenses(<<~RUBY)
1 - rand(0...limit)
RUBY
end

it 'does not register an offense when using rand(irange).succ with a non-integer range value' do
expect_no_offenses(<<~RUBY)
rand(0..limit).succ
RUBY
end

it 'does not register an offense when using rand(erange).pred with a non-integer range value' do
expect_no_offenses(<<~RUBY)
rand(0...limit).pred
RUBY
end

it 'does not register an offense when using range with double dots' do
expect_no_offenses('rand(1..6)')
end
Expand Down

0 comments on commit 058d541

Please sign in to comment.