Skip to content

Commit

Permalink
fix issue with in_rescue? that missed exits outside of rescues
Browse files Browse the repository at this point in the history
  • Loading branch information
dorkrawk authored and koic committed Apr 27, 2022
1 parent b812c1f commit ffd599c
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#695](https://github.com/rubocop/rubocop-rails/pull/695): Fixes a false negative where the `in_rescue?` check would bypass situations where the return was inside a transaction but outside of a rescue. ([@dorkrawk][])
10 changes: 9 additions & 1 deletion lib/rubocop/cop/rails/transaction_exit_statement.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,14 @@ class TransactionExitStatement < Base
({return | break | send nil? :throw} ...)
PATTERN

def_node_matcher :rescue_body_return_node?, <<~PATTERN
(:resbody ...
...
({return | break | send nil? :throw} ...)
...
)
PATTERN

def on_send(node)
return unless (parent = node.parent)
return unless parent.block_type? && parent.body
Expand Down Expand Up @@ -80,7 +88,7 @@ def statement(statement_node)
end

def in_rescue?(statement_node)
statement_node.ancestors.find(&:rescue_type?)
statement_node.ancestors.any? { |n| rescue_body_return_node?(n) }
end

def nested_block?(statement_node)
Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/cop/rails/transaction_exit_statement_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,17 @@
RUBY
end

it 'registers an officense when `return` is used outside of a `rescue`' do
expect_offense(<<~RUBY)
ApplicationRecord.transaction do
return if user.active?
^^^^^^ Exit statement `return` is not allowed. Use `raise` (rollback) or `next` (commit).
rescue
pass
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 ffd599c

Please sign in to comment.