Ruby on Rails Q & A

 

How to use environment variables in Rails?

In Rails, environment variables serve as an efficient method to manage configuration settings, particularly sensitive information such as API keys, database credentials, and secret tokens. These variables ensure that such information is kept out of the codebase, offering both security and flexibility. Here’s how to utilize environment variables in Rails:

 

  1. Accessing Environment Variables:

In Rails, you can access environment variables using the `ENV` object, a hash-like accessor. For example, to fetch the value of a variable named `DATABASE_PASSWORD`, you’d use `ENV[“DATABASE_PASSWORD”]`.

 

  1. Setting Environment Variables:

For local development, you can set environment variables directly in your terminal or shell. For instance, in a UNIX-like system, you might use:

 

```

export DATABASE_PASSWORD=mysecretpassword

```

 

However, this method only temporarily sets the variable, and it’ll be lost once the session ends.

 

  1. Using the `dotenv` Gem:

 

For a more organized approach, especially during development, the `dotenv` gem is invaluable. After adding it to your Gemfile and bundling, you can create a `.env` file in your Rails root directory. Inside this file, define your variables:

 


```

DATABASE_PASSWORD=mysecretpassword

```

 

The `dotenv` gem loads this file, making these variables available via the `ENV` object. Make sure to add `.env` to your `.gitignore` to ensure it doesn’t get committed to version control.

 

  1. Deployment:

When deploying your Rails application, you’ll need to set these environment variables on the server or the platform you’re deploying to. Most hosting platforms, like Heroku, AWS, or DigitalOcean App Platform, provide interfaces or CLI commands to set environment variables.

 

  1. Keeping Secrets Safe:

Remember that environment variables are meant to keep sensitive information secure. Never hard-code secrets or keys directly in your application. By using environment variables, you ensure that each deployment environment (development, staging, production) can have its unique settings, and you keep sensitive data out of your version-controlled codebase.

 

Environment variables in Rails offer a secure and flexible approach to manage configurations and secrets, enhancing both the security and adaptability of your application.

Previously at
Flag Argentina
Brazil
time icon
GMT-3
Senior Software Engineer with a focus on remote work. Proficient in Ruby on Rails. Expertise spans y6ears in Ruby on Rails development, contributing to B2C financial solutions and data engineering.