Keep database passwords and API keys out of your Rails codebase by storing them in a .env file that is excluded from git.
Use separate .env.development and .env.production files so the app picks up the right settings in each environment automatically.
Add dotenv to your test suite so environment variable changes made during a test are rolled back after it finishes, preventing test pollution.
Load a .env file before running a command-line script without modifying the script itself, using the included CLI tool.
Dotenv is a Ruby gem that loads configuration values from a plain text file called .env into your application's environment when it starts up. The problem it solves is common: you have settings like database passwords, API keys, or storage bucket names that change between your laptop, your test server, and your production server. Putting those values in a .env file and keeping that file off version control means each environment can have its own settings without touching the actual code. In a Rails application, dotenv loads automatically when the app boots and follows a specific priority order across multiple files. A file like .env.development.local takes precedence over .env.development, which takes precedence over the shared .env file. Local override files are meant to stay out of source control, while the shared environment files can be committed to the repository as safe defaults. The gem also supports a few convenient features in the .env file itself. You can reference other variables using $VAR syntax, substitute in the output of a shell command using $(command), write multi-line values with double quotes, and add comments with #. If a required variable is missing, you can configure dotenv to raise an error rather than silently continuing. For testing, dotenv version 3 added automatic environment restoration: any changes made to environment variables during a test are rolled back after that test finishes, preventing one test from affecting another. Outside of Rails, it works with Sinatra and plain Ruby apps by requiring the library early in the startup process. A command-line tool is also included so you can load a .env file before running any script without modifying the script itself.
← bkeepers on gitmyhub — every repo by this author, as a profile.
Verify against the repo before relying on details.