Rails credentials: local overrides

 Â· 
rails secrets

In the past I have used dotenv to manage secrets locally in .env files and environment variables on servers. It has served me very well. Lately I have been using Rails’ credential feature and it has the benefit that you don’t need to manage environment variables on machines anymore so your Rails app is more portable.

So you have split your credentials in environments: development, test, production, but what if you need to test some service with a real API key? In my case I was trying to test sending messages to Whatsapp using some service’s API.

With dotenv you’d just create a .env.local or .env.development.local with some override in it:

SOME_SERVICE_API_KEY=1234567890

For Rails credentials I came up with the following initializer that allows me to add a local override:

# config/initializers/01_local_credentials.rb
if Rails.env.development?
Rails.application.credentials.some_service[:api_key] = '1234567890'
end

Be sure to add this to either .gitignore or .git/info/exclude so that you don’t commit secrets. .git/info/exclude is probably a good idea either way because it will prevent you from accidentally committing the secrets when you switch to a branch that doesn’t have the change in .gitignore yet.