Skip to content

Commit 4fd3017

Browse files
hoshinotsuyoshikoic
authored andcommitted
Make Rails/FindBy aware of safe navigation operator
1 parent e965fd9 commit 4fd3017

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

lib/rubocop/cop/rails/find_by.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ class FindBy < Cop
2020
TARGET_SELECTORS = %i[first take].freeze
2121

2222
def_node_matcher :where_first?, <<-PATTERN
23-
(send (send _ :where ...) {:first :take})
23+
(send ({send csend} _ :where ...) {:first :take})
2424
PATTERN
2525

2626
def on_send(node)
@@ -32,6 +32,7 @@ def on_send(node)
3232
add_offense(node, location: range,
3333
message: format(MSG, method: node.method_name))
3434
end
35+
alias on_csend on_send
3536

3637
def autocorrect(node)
3738
# Don't autocorrect where(...).first, because it can return different

spec/rubocop/cop/rails/find_by_spec.rb

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,25 @@
2828
it 'does not register an offense when using find_by' do
2929
expect_no_offenses('User.find_by(id: x)')
3030
end
31+
32+
it 'autocorrects where.take to find_by' do
33+
new_source = autocorrect_source('User.where(id: x).take')
34+
35+
expect(new_source).to eq('User.find_by(id: x)')
36+
end
37+
38+
it 'does not autocorrect where.first' do
39+
new_source = autocorrect_source('User.where(id: x).first')
40+
41+
expect(new_source).to eq('User.where(id: x).first')
42+
end
43+
44+
context 'when using safe navigation operator', :ruby23 do
45+
it 'registers an offense when using `#first`' do
46+
expect_offense(<<-RUBY.strip_indent)
47+
User&.where(id: x).first
48+
^^^^^^^^^^^^^^^^^^ Use `find_by` instead of `where.first`.
49+
RUBY
50+
end
51+
end
3152
end

0 commit comments

Comments
 (0)