Revibalog

home

ENV.assert

07 Feb 2014

Forgetting to set an environment variable will result in a nil value where it's not expected. In certain situations the problem won't manifest immediately. For instance, in a Rails app we won't find out there's a missing mailer host until we try to send an email:

# config/environments/production.rb
config.action_mailer.default_url_options = { host: ENV['ACTION_MAILER_HOST'] }

A solution I've expermimented with is to immediately fail when a required environment variable is not set. Early on in the application boot process, usually the top of config/application.rb, I'll define a method on ENV:

def ENV.assert(key)
  ENV[key] or raise "missing required ENV value for key: #{key}"
end

The implementation could be more robust, but I've found raising on a falsy value to be sufficient. The usage is simple:

config.action_mailer.default_url_options = { host: ENV.assert('ACTION_MAILER_HOST') }

During the initialization process, any missing, required environment variables will raise an exception with a helpful message:

/path/to/myapp/config/environments/development.rb:6:in `assert': 
missing required ENV value for key: ACTION_MAILER_HOST (RuntimeError)

It may be a bit heavy handed, but failing fast is a good thing when it comes to configuration issues.



comments powered by Disqus