Class: RuboCop::Cop::Apartment::PreferBlockSwitch

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/apartment/prefer_block_switch.rb

Overview

Nudges callers away from Apartment::Tenant.switch! toward the block-form switch, which restores context via ensure. reset is intentionally not flagged (it is the sanctioned unguarded path back to the default tenant).

Examples:

# bad
Apartment::Tenant.switch!('acme')

# good
Apartment::Tenant.switch('acme') { ... }

Constant Summary collapse

MSG =
'Use the block-form `Apartment::Tenant.switch(tenant) { ... }` ' \
'instead of `switch!`.'
RESTRICT_ON_SEND =

Only invoke on_send for switch! — keeps the cop off the hot path (RuboCop would otherwise call on_send for every method call linted).

%i[switch!].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



29
30
31
32
33
34
35
# File 'lib/rubocop/cop/apartment/prefer_block_switch.rb', line 29

def on_send(node)
  return unless tenant_bang_switch?(node)

  # Highlight the `switch!` selector — stable range regardless of receiver
  # prefix or arguments.
  add_offense(node.loc.selector)
end

#tenant_bang_switch?(node) ⇒ Object



25
26
27
# File 'lib/rubocop/cop/apartment/prefer_block_switch.rb', line 25

def_node_matcher :tenant_bang_switch?, <<~PATTERN
  (send (const (const {nil? cbase} :Apartment) :Tenant) :switch! ...)
PATTERN