Class: RuboCop::Cop::DevDoc::Rails::ApplicationRecordTransaction

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/dev_doc/rails/application_record_transaction.rb

Overview

Use ‘ApplicationRecord.transaction` instead of `SomeModel.transaction` outside model files.

## Rationale When using ‘transaction` outside of a model, `SomeModel.transaction` reads as if there is a meaningful link to that model when there isn’t. ‘ApplicationRecord.transaction` is functionally identical and makes it clear that the transaction has no special relationship to any particular model.

❌  (in a controller or service)
Checklist.transaction do
  ...
end

✔️
ApplicationRecord.transaction do
  ...
end

Examples:

# bad (in a controller or service)
Order.transaction do
  order.save!
end

# good
ApplicationRecord.transaction do
  order.save!
end

Constant Summary collapse

ALLOWED_RECEIVERS =
%w[ApplicationRecord ActiveRecord::Base].freeze
MSG =
'Use `ApplicationRecord.transaction` instead of `%<receiver>s.transaction` outside model files.'.freeze
RESTRICT_ON_SEND =
%i[transaction].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



42
43
44
45
46
47
48
49
50
51
# File 'lib/rubocop/cop/dev_doc/rails/application_record_transaction.rb', line 42

def on_send(node)
  receiver = node.receiver
  return if receiver.nil?
  return unless receiver.const_type?
  return if ALLOWED_RECEIVERS.include?(receiver.source)

  add_offense(receiver, message: format(MSG, receiver: receiver.source)) do |corrector|
    corrector.replace(receiver, 'ApplicationRecord')
  end
end