Skip to content

Commit

Permalink
Merge pull request #1258 from Earlopain/false-positive-for-rails-save…
Browse files Browse the repository at this point in the history
…-bang

[Fix #1230] Fix a false positive for `Rails/SaveBang` if `persisted?` is checked on parenthesised expression.
  • Loading branch information
koic committed Mar 24, 2024
2 parents af30389 + c568fa8 commit f5c378a
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
1 change: 1 addition & 0 deletions changelog/fix_false_positive_for_rails_save_bang.md
@@ -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
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
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

0 comments on commit f5c378a

Please sign in to comment.