Skip to content

Commit

Permalink
[Fix rubocop#658] Fix a false positive for `Rails/TransactionExitStat…
Browse files Browse the repository at this point in the history
…ement`

Fixes rubocop#658.

This PR fixes a false positive for `Rails/TransactionExitStatement`
when `raise` is used in `loop` in transactions.
  • Loading branch information
koic committed Mar 16, 2022
1 parent 8373c5a commit de664fa
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 7 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#658](https://github.com/rubocop/rubocop-rails/issues/658): Fix a false positive for `Rails/TransactionExitStatement` when `raise` is used in `loop` in transactions. ([@koic][])
22 changes: 15 additions & 7 deletions lib/rubocop/cop/rails/transaction_exit_statement.rb
Original file line number Diff line number Diff line change
Expand Up @@ -59,18 +59,26 @@ def on_send(node)
return unless parent&.block_type?

exit_statements(parent.body).each do |statement_node|
statement = if statement_node.return_type?
'return'
elsif statement_node.break_type?
'break'
else
statement_node.method_name
end
next unless statement_node.ancestors.find(&:block_type?).method?(:transaction)

statement = statement(statement_node)
message = format(MSG, statement: statement)

add_offense(statement_node, message: message)
end
end

private

def statement(statement_node)
if statement_node.return_type?
'return'
elsif statement_node.break_type?
'break'
else
statement_node.method_name
end
end
end
end
end
Expand Down
10 changes: 10 additions & 0 deletions spec/rubocop/cop/rails/transaction_exit_statement_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,14 @@
end
RUBY
end

it 'does not register an offense when `raise` is used in `loop` in transactions' do
expect_no_offenses(<<~RUBY)
ApplicationRecord.transaction do
loop do
break if condition
end
end
RUBY
end
end

0 comments on commit de664fa

Please sign in to comment.