Accessing Environment Variables in Rails

Using ENV['key'] instead of ENV.fetch('key') can be considered a bad practice because of the following reasons:

  1. Error handling: ENV['key'] returns nil 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 unexpected nil value.

    In contrast, ENV.fetch('key') raises a KeyError 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.

  2. 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 or nil.

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.