Skip to content

Commit

Permalink
Merge pull request #674 from koic/fix_false_positive_for_rails_transa…
Browse files Browse the repository at this point in the history
…ction_exit_statement

[Fix #669] Fix a false positive for `Rails/TransactionExitStatement`
  • Loading branch information
koic committed Mar 17, 2022
2 parents d331c8d + d9ec02d commit 10e478f
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#669](https://github.com/rubocop/rubocop-rails/issues/669): Fix a false positive for `Rails/TransactionExitStatement` when `return` is used in `rescue`. ([@koic][])
8 changes: 7 additions & 1 deletion lib/rubocop/cop/rails/transaction_exit_statement.rb
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def on_send(node)
return unless parent.block_type? && parent.body

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

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

def in_rescue?(statement_node)
statement_node.ancestors.find(&:rescue_type?)
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
9 changes: 9 additions & 0 deletions spec/rubocop/cop/rails/transaction_exit_statement_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,15 @@
RUBY
end

it 'does not register an offense when `return` is used in `rescue`' do
expect_no_offenses(<<~RUBY)
ApplicationRecord.transaction do
rescue
return do_something
end
RUBY
end

it 'does not register an offense when transaction block is empty' do
expect_no_offenses(<<~RUBY)
ApplicationRecord.transaction do
Expand Down

0 comments on commit 10e478f

Please sign in to comment.