|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +module RuboCop |
| 4 | + module Cop |
| 5 | + module Rails |
| 6 | + # This cop checks for the use of exit statements (namely `return`, |
| 7 | + # `break` and `throw`) in transactions. This is due to the eventual |
| 8 | + # unexpected behavior when using ActiveRecord >= 7, where transactions |
| 9 | + # exitted using these statements are being rollbacked rather than |
| 10 | + # committed (pre ActiveRecord 7 behavior). |
| 11 | + # |
| 12 | + # As alternatives, it would be more intuitive to explicitly raise an |
| 13 | + # error when rollback is desired, and to use `next` when commit is |
| 14 | + # desired. |
| 15 | + # |
| 16 | + # @example |
| 17 | + # # bad |
| 18 | + # ApplicationRecord.transaction do |
| 19 | + # return if user.active? |
| 20 | + # end |
| 21 | + # |
| 22 | + # # bad |
| 23 | + # ApplicationRecord.transaction do |
| 24 | + # break if user.active? |
| 25 | + # end |
| 26 | + # |
| 27 | + # # bad |
| 28 | + # ApplicationRecord.transaction do |
| 29 | + # throw if user.active? |
| 30 | + # end |
| 31 | + # |
| 32 | + # # good |
| 33 | + # ApplicationRecord.transaction do |
| 34 | + # # Rollback |
| 35 | + # raise "User is active" if user.active? |
| 36 | + # end |
| 37 | + # |
| 38 | + # # good |
| 39 | + # ApplicationRecord.transaction do |
| 40 | + # # Commit |
| 41 | + # next if user.active? |
| 42 | + # end |
| 43 | + # |
| 44 | + # @see https://github.com/rails/rails/commit/15aa4200e083 |
| 45 | + class TransactionExitStatement < Base |
| 46 | + MSG = <<~MSG.chomp |
| 47 | + Exit statement `%<statement>s` is not allowed. Use `raise` (rollback) or `next` (commit). |
| 48 | + MSG |
| 49 | + |
| 50 | + RESTRICT_ON_SEND = %i[transaction].freeze |
| 51 | + |
| 52 | + def_node_search :exit_statements, <<~PATTERN |
| 53 | + ({return | break | send nil? :throw} ...) |
| 54 | + PATTERN |
| 55 | + |
| 56 | + def on_send(node) |
| 57 | + parent = node.parent |
| 58 | + |
| 59 | + return unless parent&.block_type? |
| 60 | + |
| 61 | + 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 |
| 69 | + message = format(MSG, statement: statement) |
| 70 | + |
| 71 | + add_offense(statement_node, message: message) |
| 72 | + end |
| 73 | + end |
| 74 | + end |
| 75 | + end |
| 76 | + end |
| 77 | +end |
0 commit comments