A Rails app with customers deploys to a minimum of three environments: development, staging and production.
Development - local environment of the app on your machine
Staging - a pit stop on the way to production; ensure code changes are functional before proceeding to production
Production - where your users interact with the app
Here's a contrived example - you wouldn't use the same Stripe API key for development and production. That would mix dummy data on your local machine with real user data! Separation of concerns doesn't just apply to software, ya know.
If only there's a way to allow the environment to determine the value..
Stripe.api_key = ENV["STRIPE_API_KEY"]
# .env STRIPE_API_KEY=xxxx-xxxxxxxxxxx
You can include a library like dotenv from Github to your project.
ENV["STRIPE_API_KEY"] reads from
.env that you can create in the root of your project directory. If
STRIPE_API_KEY set, that's the value it'll use in your local development environment.
When deploying to staging and production, Heroku has a mechanism to get and set keys as well.
$ heroku config -r staging => ... list of ENVs for staging
This prints out a list of environment variables for staging separated by new lines. You could pass in production as a remote as well and get production variables.
Write it once and your code can read from the environment 🆗
BONUS: If a default value is of interesting to you, implementing it is simple!
ENV is a hash (more or less). Therefore, you can ask it
Hash#fetch which allows a default.
Notice the use of parenthesis when allowing a default.