Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix an error for Rails/FindBy when calling #first or #take on a Range object. #510

Merged
merged 1 commit into from
Jun 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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