Skip to content

Commit d2ce35d

Browse files
authored
Merge pull request #662 from koic/fix_a_false_positive_for_rails_transaction_exit_statement
[Fix #658] Fix a false positive for `Rails/TransactionExitStatement`
2 parents 8373c5a + 583175c commit d2ce35d

File tree

3 files changed

+26
-7
lines changed

3 files changed

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

lib/rubocop/cop/rails/transaction_exit_statement.rb

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -59,18 +59,26 @@ def on_send(node)
5959
return unless parent&.block_type?
6060

6161
exit_statements(parent.body).each do |statement_node|
62-
statement = if statement_node.return_type?
63-
'return'
64-
elsif statement_node.break_type?
65-
'break'
66-
else
67-
statement_node.method_name
68-
end
62+
next unless statement_node.ancestors.find(&:block_type?).method?(:transaction)
63+
64+
statement = statement(statement_node)
6965
message = format(MSG, statement: statement)
7066

7167
add_offense(statement_node, message: message)
7268
end
7369
end
70+
71+
private
72+
73+
def statement(statement_node)
74+
if statement_node.return_type?
75+
'return'
76+
elsif statement_node.break_type?
77+
'break'
78+
else
79+
statement_node.method_name
80+
end
81+
end
7482
end
7583
end
7684
end

spec/rubocop/cop/rails/transaction_exit_statement_spec.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,4 +43,14 @@
4343
end
4444
RUBY
4545
end
46+
47+
it 'does not register an offense when `break` is used in `loop` in transactions' do
48+
expect_no_offenses(<<~RUBY)
49+
ApplicationRecord.transaction do
50+
loop do
51+
break if condition
52+
end
53+
end
54+
RUBY
55+
end
4656
end

0 commit comments

Comments
 (0)