Class: RuboCop::Cop::ContainerEnv::PreferContainerEnv

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/container_env/prefer_container_env.rb

Overview

Flags direct ‘ENV` reads and suggests `ContainerEnv` instead.

‘ContainerEnv` transparently adds Docker secrets support and optional caching on top of `ENV`. Accessing `ENV` directly bypasses both features.

Write access (‘ENV[]=`) and enumeration methods (`to_h`, `each`, `replace`, etc.) are intentionally not flagged — they have no `ContainerEnv` equivalent and are commonly used in test setup.

Examples:

# bad
ENV['DATABASE_URL']
ENV.fetch('DATABASE_URL')
ENV.fetch('DATABASE_URL', 'postgres://localhost/dev')
ENV.fetch('DATABASE_URL') { |k| "default for #{k}" }

# good
ContainerEnv['DATABASE_URL']
ContainerEnv.fetch('DATABASE_URL')
ContainerEnv.fetch('DATABASE_URL', 'postgres://localhost/dev')
ContainerEnv.fetch('DATABASE_URL') { |k| "default for #{k}" }

Constant Summary collapse

MSG =
'Use `ContainerEnv` instead of direct `ENV` access.'
RESTRICT_ON_SEND =

Restricts which send nodes are delivered to on_send. Only read/check methods that ContainerEnv implements are listed.

%i[[] fetch].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



40
41
42
43
44
45
46
# File 'lib/rubocop/cop/container_env/prefer_container_env.rb', line 40

def on_send(node)
  return unless env_const?(node.receiver)

  add_offense(node) do |corrector|
    corrector.replace(node.receiver, 'ContainerEnv')
  end
end