ENV var do's and dont's

Goofus reads in his ENV vars at runtime and gets hundreds of bugsnag notifications and customer complaints.

class MyClass
  def my_method
    ENV['important_var'] + 1
  end

Gallant reads in his ENV vars with fetch at load time and the devops team notices the failed deployment and add the env var. His customers are happy.

class MyClass
  VAR = ENV.fetch('important_var')
  def my_method
    VAR + 1
  end

Goofus sets default values for environments in the classes and confuses his coworkers with conditionals.

class MyClass
  ENV['important_var'] ||= 'hello' if Rails.env.development?
  ENV['important_var'] ||= 'world' if Rails.env.test?

Gallant sets default values in the config/environments files. His coworkers know exactly where to look to understand the env.

# config/environments/development.rb
ENV['important_var'] ||= 'hello'

# config/environments/test.rb
ENV['important_var'] ||= 'world'

Goofus uses string values to represent boolean flags and keeps his coworkers guessing.

my_flag = ENV['MY_FLAG'] == 't' || ENV['MY_FLAG'] == 'true'

Gallant uses nil for false so that setting it to any string is true. His coworkers appreciate the flexibility.

my_flag = ENV['MY_FLAG'].present?

22