Skip to content

Commit

Permalink
Merge pull request #1421 from ydakuka/fix/enhance-rails-save-bang-to-…
Browse files Browse the repository at this point in the history
…properly-handle-instance-variables

[Fix #1228] Enhance `Rails/SaveBang` to properly handle instance variables
  • Loading branch information
koic authored Jan 19, 2025
2 parents 160d624 + 48233de commit e5dce3a
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#1228](https://github.com/rubocop/rubocop-rails/issues/1228): Enhance `Rails/SaveBang` to properly handle instance variables. ([@ydakuka][])
5 changes: 3 additions & 2 deletions lib/rubocop/cop/rails/save_bang.rb
Original file line number Diff line number Diff line change
Expand Up @@ -328,8 +328,9 @@ def explicit_return?(node)
end

def return_value_assigned?(node)
assignment = assignable_node(node).parent
assignment&.lvasgn_type?
return false unless (assignment = assignable_node(node).parent)

assignment.assignment?
end

def persist_method?(node, methods = RESTRICT_ON_SEND)
Expand Down
50 changes: 50 additions & 0 deletions spec/rubocop/cop/rails/save_bang_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -668,6 +668,56 @@ def whatever
RUBY
end

it "does not register an offense when using persisted? after #{method} to a local variable" do
expect_no_offenses(<<~RUBY)
user = User.#{method}
if user.persisted?
foo
end
RUBY
end

it "does not register an offense when using persisted? after #{method} to an instance variable" do
expect_no_offenses(<<~RUBY)
@user = User.#{method}
if @user.persisted?
foo
end
RUBY
end

it "does not register an offense when using persisted? after #{method} to a global variable" do
expect_no_offenses(<<~RUBY)
$user = User.#{method}
if $user.persisted?
foo
end
RUBY
end

it "does not register an offense when using persisted? after #{method} for multiple assignments" do
expect_no_offenses(<<~RUBY)
a, b = User.#{method}, User.new
if a.persisted?
foo
end
RUBY
end

it "does not register an offense when using persisted? after #{method} for conditional assignments" do
expect_no_offenses(<<~RUBY)
user ||= User.#{method}
if user.persisted?
foo
end
RUBY
end

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

0 comments on commit e5dce3a

Please sign in to comment.