Last Updated: February 25, 2016
·
420
· jamesmartin

Missing ENV Variables Return Early

Here's a quick way to bail out of a method or initializer when a required ENV variable is missing and provide a useful error message.

required_vars = %w(FOO BAR BAZ QUUX)
missing_vars = required_vars - ENV.keys
raise ArgumentError.new("The following ENV variables are required: #{missing_vars}") if missing_vars.any?

Using Ruby Array's built-in subtract method, we get the difference between the list of variables we require and those set.

You can use this to guard against missing options in methods, too.