Class: RuboCop::Cop::Rails::EnvironmentVariableAccess

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/rails/environment_variable_access.rb

Overview

Looks for direct access to environment variables through the ‘ENV` variable within the application code. This can lead to runtime errors due to misconfiguration that could have been discovered at boot time if the environment variables were loaded as part of initialization and copied into the application’s configuration or secrets. The cop can be configured to allow either reads or writes if required.

Examples:

# good
Rails.application.config.foo
Rails.application.config.x.foo.bar
Rails.application.secrets.foo
Rails.application.config.foo = "bar"

AllowReads: false (default)

# bad
ENV["FOO"]
ENV.fetch("FOO")

AllowReads: true

# good
ENV["FOO"]
ENV.fetch("FOO")

AllowWrites: false (default)

# bad
ENV["FOO"] = "bar"

AllowWrites: true

# good
ENV["FOO"] = "bar"

Constant Summary collapse

READ_MSG =
'Do not read from `ENV` directly post initialization.'
WRITE_MSG =
'Do not write to `ENV` directly post initialization.'

Instance Method Summary collapse

Instance Method Details

#on_const(node) ⇒ Object



41
42
43
44
# File 'lib/rubocop/cop/rails/environment_variable_access.rb', line 41

def on_const(node)
  add_offense(node, message: READ_MSG) if env_read?(node) && !allow_reads?
  add_offense(node, message: WRITE_MSG) if env_write?(node) && !allow_writes?
end