DEV Community

Cover image for ENV var do's and dont's
Kelly Stannard
Kelly Stannard

Posted on

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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?
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

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

my_flag = ENV['MY_FLAG'] == 't' || ENV['MY_FLAG'] == 'true'
Enter fullscreen mode Exit fullscreen mode

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?
Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
erinposting profile image
Erin Bensinger

Haven't heard from my good friends Goofus and Gallant in years! 😂

Some comments may only be visible to logged-in visitors. Sign in to view all comments.