Skip to content

Commit 10e478f

Browse files
authored
Merge pull request #674 from koic/fix_false_positive_for_rails_transaction_exit_statement
[Fix #669] Fix a false positive for `Rails/TransactionExitStatement`
2 parents d331c8d + d9ec02d commit 10e478f

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#669](https://github.com/rubocop/rubocop-rails/issues/669): Fix a false positive for `Rails/TransactionExitStatement` when `return` is used in `rescue`. ([@koic][])

lib/rubocop/cop/rails/transaction_exit_statement.rb

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def on_send(node)
5858
return unless parent.block_type? && parent.body
5959

6060
exit_statements(parent.body).each do |statement_node|
61-
next if statement_node.break_type? && nested_block?(statement_node)
61+
next if in_rescue?(statement_node) || nested_block?(statement_node)
6262

6363
statement = statement(statement_node)
6464
message = format(MSG, statement: statement)
@@ -79,7 +79,13 @@ def statement(statement_node)
7979
end
8080
end
8181

82+
def in_rescue?(statement_node)
83+
statement_node.ancestors.find(&:rescue_type?)
84+
end
85+
8286
def nested_block?(statement_node)
87+
return false unless statement_node.break_type?
88+
8389
!statement_node.ancestors.find(&:block_type?).method?(:transaction)
8490
end
8591
end

spec/rubocop/cop/rails/transaction_exit_statement_spec.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,15 @@
7676
RUBY
7777
end
7878

79+
it 'does not register an offense when `return` is used in `rescue`' do
80+
expect_no_offenses(<<~RUBY)
81+
ApplicationRecord.transaction do
82+
rescue
83+
return do_something
84+
end
85+
RUBY
86+
end
87+
7988
it 'does not register an offense when transaction block is empty' do
8089
expect_no_offenses(<<~RUBY)
8190
ApplicationRecord.transaction do

0 commit comments

Comments
 (0)