Class: RuboCop::Cop::Axn::AmbientContextBypass

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/axn/ambient_context_bypass.rb

Overview

Flags direct reads of Current.<attr> and steers toward declaring the dependency explicitly with expects :<attr>, on: :ambient_context. Opt-in (see README).

Only fires inside a class/module that include Axnexpects ..., on: :ambient_context is only a fix available to Axn classes, so flagging a Current read anywhere else (controllers, models, plain jobs) would be an unfixable false positive.

Examples:

# bad
class ChargeCard
  include Axn
  def call = do_thing(Current.company)
end

# good
class ChargeCard
  include Axn
  expects :company, on: :ambient_context
  def call = do_thing(company)
end

Constant Summary collapse

MSG =
"Read ambient state via `expects :%<attr>s, on: :ambient_context` instead of `Current` directly."
CURRENT_API_METHODS =

ActiveSupport::CurrentAttributes class/lifecycle API — these are not ambient-attribute reads, so flagging them (and suggesting a nonsense expects :reset, ...) would break normal request/test cleanup lint.

%i[
  reset reset_all clear_all set instance attributes before_reset after_reset resets attribute
].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



46
47
48
49
50
51
52
53
54
55
# File 'lib/rubocop/cop/axn/ambient_context_bypass.rb', line 46

def on_send(node)
  # Reads only: skip `Current.foo(args)` and the setter `Current.foo = x`.
  return if node.arguments.any? || node.assignment_method?
  return if CURRENT_API_METHODS.include?(node.method_name)
  return unless within_axn_class?(node)

  current_read(node) do |attr|
    add_offense(node, message: format(MSG, attr:))
  end
end