Skip to content

Commit

Permalink
Merge pull request #510 from johnsyweb/paj/bug-repro
Browse files Browse the repository at this point in the history
Fix an error for `Rails/FindBy` when calling `#first` or `#take` on a `Range` object.
  • Loading branch information
koic authored Jun 24, 2021
2 parents 41597b0 + 3ed8153 commit 9f6fcdc
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
### Bug fixes

* [#509](https://github.com/rubocop/rubocop-rails/pull/509): Fix an error for `Rails/ReflectionClassName` when using `class_name: to_s`. ([@skryukov][])
* [#510](https://github.com/rubocop/rubocop-rails/pull/510): Fix an error for `Rails/FindBy` when calling `#first` or `#take` on a `Range` object. ([@johnsyweb][])
* [#507](https://github.com/rubocop/rubocop-rails/pull/507): Fix an error for `Rails/FindBy` when calling `take` after block. ([@koic][])
* [#504](https://github.com/rubocop/rubocop-rails/issues/504): Fix a false positive for `Rails/FindBy` when receiver is not an Active Record. ([@nvasilevski][])

Expand Down Expand Up @@ -413,3 +414,4 @@
[@aesthetikx]: https://github.com/aesthetikx
[@nvasilevski]: https://github.com/nvasilevski
[@skryukov]: https://github.com/skryukov
[@johnsyweb]: https://github.com/johnsyweb
9 changes: 7 additions & 2 deletions lib/rubocop/cop/rails/find_by.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ class FindBy < Base
RESTRICT_ON_SEND = %i[first take].freeze

def on_send(node)
receiver = node.receiver
return unless receiver&.method?(:where)
return unless where_method?(node.receiver)
return if ignore_where_first? && node.method?(:first)

range = range_between(node.receiver.loc.selector.begin_pos, node.loc.selector.end_pos)
Expand All @@ -46,6 +45,12 @@ def on_send(node)

private

def where_method?(receiver)
return false unless receiver

receiver.respond_to?(:method?) && receiver.method?(:where)
end

def autocorrect(corrector, node)
return if node.method?(:first)

Expand Down
12 changes: 12 additions & 0 deletions spec/rubocop/cop/rails/find_by_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -92,5 +92,17 @@
RUBY
end
end

context 'when method is Range#first' do
it 'does not register an offense' do
expect_no_offenses('(1..2).first')
end
end

context 'when method is Range#take' do
it 'does not register an offense' do
expect_no_offenses('(1..2).take(1)')
end
end
end
end

0 comments on commit 9f6fcdc

Please sign in to comment.