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 a false negative for Rails/TransactionExitStatement #696

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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#696](https://github.com/rubocop/rubocop-rails/pull/696): Fix a false negative for `Rails/TransactionExitStatement` when `return` is used in `rescue`. ([@koic][])
8 changes: 1 addition & 7 deletions lib/rubocop/cop/rails/transaction_exit_statement.rb
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def on_send(node)
return unless parent.block_type? && parent.body

exit_statements(parent.body).each do |statement_node|
next if in_rescue?(statement_node) || nested_block?(statement_node)
next if statement_node.break_type? && nested_block?(statement_node)

statement = statement(statement_node)
message = format(MSG, statement: statement)
Expand All @@ -87,13 +87,7 @@ def statement(statement_node)
end
end

def in_rescue?(statement_node)
statement_node.ancestors.any? { |n| rescue_body_return_node?(n) }
end

def nested_block?(statement_node)
return false unless statement_node.break_type?

!statement_node.ancestors.find(&:block_type?).method?(:transaction)
end
end
Expand Down
5 changes: 3 additions & 2 deletions spec/rubocop/cop/rails/transaction_exit_statement_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,12 @@
RUBY
end

it 'does not register an offense when `return` is used in `rescue`' do
expect_no_offenses(<<~RUBY)
it 'registers an offense when `return` is used in `rescue`' do
expect_offense(<<~RUBY)
ApplicationRecord.transaction do
rescue
return do_something
^^^^^^^^^^^^^^^^^^^ Exit statement `return` is not allowed. Use `raise` (rollback) or `next` (commit).
end
RUBY
end
Expand Down