Managing ENV variables in Rails
20 Oct 14
In this tutorial, I will guide you on an easy method on how to set up environment config variables in Rails.
Often when developing Rails applications, you will find a need to setup a couple of environment variables to store secure information such as passwords, api keys, secrets, etc. This is done especially when your application's code is open source and you don't want people who access your code to see your passwords, secret keys etc. Setting this variables as environmental variables is safe as these values are stored at the operating system level that your app has access to.
There are many solutions out there like adding this keys in your
.zrshrc, using gems such as Dotenv and Figaro. You can easily mess up system configuration files when using Bash or Zsh profiles. The Gems are great but if you want zero gem dependencies to manage your environment variables then I have a simple straight forward solution that I use myself when working on this kind of projects.
Start of by creating a new file in your
config directory of your rails app called
application.yml. You can give it any name you like but in our case let's just call it so. You can then add all your keys in this file. You can even group them by environment. Here is an example
With this, we can export all this values as environmental variables by adding the following code in your
application.rb file inside the
You can now access any values like this
I think this is a much cleaner and dynamic way to manage your environmental variables. Remember to add the file (application.yml in our case) that contains your keys and secrets to your
.gitignore file to avoid commiting it to version control. I'd be glad to hear what you think about this procedure in the comments section below. Thank you so much for reading. Happy hacking!!