Class: RuboCop::Cop::ThreadSafety::EnvMutation

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/thread_safety/env_mutation.rb

Overview

Avoid mutating ENV.

Environment variables are process-wide. Mutating them can affect other threads, requests, jobs, or subprocesses running in the same Ruby process.

Examples:

# bad
ENV['TZ'] = 'UTC'

# bad
ENV.update('FOO' => 'bar')

# good
system({ 'TZ' => 'UTC' }, 'date')

# good
ENV.fetch('TZ', 'UTC')

Constant Summary collapse

MSG =
'Avoid mutating `ENV` due to its process-wide effect.'
RESTRICT_ON_SEND =
%i[
  []=
  store
  update
  merge!
  replace
  delete
  delete_if
  reject!
  keep_if
  select!
  filter!
  shift
  clear
].freeze

Instance Method Summary collapse

Instance Method Details

#env_mutation?(node) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/rubocop/cop/thread_safety/env_mutation.rb', line 43

def_node_matcher :env_mutation?, <<~PATTERN
  (call
    (const {nil? cbase} :ENV)
    {
      :[]=
      :store
      :update
      :merge!
      :replace
      :delete
      :delete_if
      :reject!
      :keep_if
      :select!
      :filter!
      :shift
      :clear
    }
    ...)
PATTERN

#on_send(node) ⇒ Object Also known as: on_csend



64
65
66
67
68
# File 'lib/rubocop/cop/thread_safety/env_mutation.rb', line 64

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

  add_offense(node)
end