Accessing Environment Variables in Rails
Using ENV['key']
instead of ENV.fetch('key')
can be considered a bad practice because of the following reasons:
Error handling:
ENV['key']
returnsnil
when the specified key is not found in the environment variables. This can make it difficult to identify issues related to missing or misspelled keys, as your code may continue to execute with an unexpectednil
value.In contrast,
ENV.fetch('key')
raises aKeyError
exception if the key is not found. This makes it easier to identify issues early on, as the error message will point out the specific missing key.Default values: With
ENV.fetch('key', default_value)
, you can provide a default value that will be returned if the key is not found. This allows you to handle missing keys gracefully, without needing additional conditional logic.Using
ENV['key'] || default_value
can achieve the same result, but it’s less concise and can lead to unintended behavior when the key is present but its value is an empty string ornil
.
In summary, using ENV.fetch('key')
is generally better because it provides better error handling, allows for default values, and leads to more robust and maintainable code.