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 #1230] Fix a false positive for Rails/SaveBang if persisted? is checked on parenthesised expression. #1258

Merged
merged 1 commit into from
Mar 24, 2024
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/fix_false_positive_for_rails_save_bang.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#1230](https://github.com/rubocop/rubocop-rails/issues/1230): Fix a false positive for `Rails/SaveBang` if `persisted?` is checked on parenthesised expression. ([@earlopain][])
2 changes: 2 additions & 0 deletions lib/rubocop/cop/rails/save_bang.rb
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,8 @@ def persisted_referenced?(assignment)
end

def call_to_persisted?(node)
node = node.parent.condition if node.parenthesized_call? && node.parent.if_type?

node.send_type? && node.method?(:persisted?)
end

Expand Down
32 changes: 32 additions & 0 deletions spec/rubocop/cop/rails/save_bang_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -638,6 +638,38 @@ def whatever
RUBY
end

it "when using persisted? on the result of #{method} in if assignment" do
expect_no_offenses(<<~RUBY)
if (user = User.#{method}).persisted?
foo(user)
else
bar(user)
end
RUBY
end

it "when not using persisted? on the result of #{method} in if assignment" do
expect_offense(<<~RUBY, method: method)
if (user = User.#{method})
^{method} Use `#{method}!` instead of `#{method}` if the return value is not checked. Or check `persisted?` on model returned from `#{method}`.
foo(user)
else
bar(user)
end
RUBY
end

it "when using persisted? on the result of #{method} in elsif assignment" do
expect_no_offenses(<<~RUBY)
if something
elsif (user = User.#{method}).persisted?
foo(user)
else
bar(user)
end
RUBY
end

it "when using #{method} with `||`" do
expect_no_offenses(<<~RUBY)
def find_or_create(**opts)
Expand Down