Skip to content

Commit 48233de

Browse files
committed
[Fix #1228] Enhance Rails/SaveBang to properly handle instance variables
1 parent b80ecd9 commit 48233de

File tree

3 files changed

+54
-2
lines changed

3 files changed

+54
-2
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#1228](https://github.com/rubocop/rubocop-rails/issues/1228): Enhance `Rails/SaveBang` to properly handle instance variables. ([@ydakuka][])

lib/rubocop/cop/rails/save_bang.rb

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -328,8 +328,9 @@ def explicit_return?(node)
328328
end
329329

330330
def return_value_assigned?(node)
331-
assignment = assignable_node(node).parent
332-
assignment&.lvasgn_type?
331+
return false unless (assignment = assignable_node(node).parent)
332+
333+
assignment.assignment?
333334
end
334335

335336
def persist_method?(node, methods = RESTRICT_ON_SEND)

spec/rubocop/cop/rails/save_bang_spec.rb

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -668,6 +668,56 @@ def whatever
668668
RUBY
669669
end
670670

671+
it "does not register an offense when using persisted? after #{method} to a local variable" do
672+
expect_no_offenses(<<~RUBY)
673+
user = User.#{method}
674+
675+
if user.persisted?
676+
foo
677+
end
678+
RUBY
679+
end
680+
681+
it "does not register an offense when using persisted? after #{method} to an instance variable" do
682+
expect_no_offenses(<<~RUBY)
683+
@user = User.#{method}
684+
685+
if @user.persisted?
686+
foo
687+
end
688+
RUBY
689+
end
690+
691+
it "does not register an offense when using persisted? after #{method} to a global variable" do
692+
expect_no_offenses(<<~RUBY)
693+
$user = User.#{method}
694+
695+
if $user.persisted?
696+
foo
697+
end
698+
RUBY
699+
end
700+
701+
it "does not register an offense when using persisted? after #{method} for multiple assignments" do
702+
expect_no_offenses(<<~RUBY)
703+
a, b = User.#{method}, User.new
704+
705+
if a.persisted?
706+
foo
707+
end
708+
RUBY
709+
end
710+
711+
it "does not register an offense when using persisted? after #{method} for conditional assignments" do
712+
expect_no_offenses(<<~RUBY)
713+
user ||= User.#{method}
714+
715+
if user.persisted?
716+
foo
717+
end
718+
RUBY
719+
end
720+
671721
it "when using #{method} with `||`" do
672722
expect_no_offenses(<<~RUBY)
673723
def find_or_create(**opts)

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy