Skip to content

Commit c568fa8

Browse files
committed
[Fix #1230] Fix a false positive for Rails/SaveBang if persisted? is checked on parenthesised expression.
1 parent 650e783 commit c568fa8

File tree

3 files changed

+35
-0
lines changed

3 files changed

+35
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
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][])

lib/rubocop/cop/rails/save_bang.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,8 @@ def persisted_referenced?(assignment)
196196
end
197197

198198
def call_to_persisted?(node)
199+
node = node.parent.condition if node.parenthesized_call? && node.parent.if_type?
200+
199201
node.send_type? && node.method?(:persisted?)
200202
end
201203

spec/rubocop/cop/rails/save_bang_spec.rb

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -638,6 +638,38 @@ def whatever
638638
RUBY
639639
end
640640

641+
it "when using persisted? on the result of #{method} in if assignment" do
642+
expect_no_offenses(<<~RUBY)
643+
if (user = User.#{method}).persisted?
644+
foo(user)
645+
else
646+
bar(user)
647+
end
648+
RUBY
649+
end
650+
651+
it "when not using persisted? on the result of #{method} in if assignment" do
652+
expect_offense(<<~RUBY, method: method)
653+
if (user = User.#{method})
654+
^{method} Use `#{method}!` instead of `#{method}` if the return value is not checked. Or check `persisted?` on model returned from `#{method}`.
655+
foo(user)
656+
else
657+
bar(user)
658+
end
659+
RUBY
660+
end
661+
662+
it "when using persisted? on the result of #{method} in elsif assignment" do
663+
expect_no_offenses(<<~RUBY)
664+
if something
665+
elsif (user = User.#{method}).persisted?
666+
foo(user)
667+
else
668+
bar(user)
669+
end
670+
RUBY
671+
end
672+
641673
it "when using #{method} with `||`" do
642674
expect_no_offenses(<<~RUBY)
643675
def find_or_create(**opts)

0 commit comments

Comments
 (0)