Search code examples
ruby-on-railsrubyenvironment-variablesdotenv

How to configure the “dotenv gem” in the rails 7 application


How to configure the “dotenv gem” in the rails 7 application for the set environment variable.


Solution

  • Add the below line in the Gemfile

    gem 'dotenv-rails', require: 'dotenv/rails-now', groups: [:development]
    

    Run bundle install Add the below code just below this line Bundler.require(*Rails.groups) in the application.rb

    # Load dotenv only in development or test environment
    if ['development', 'test'].include? ENV['RAILS_ENV']
    Dotenv::Railtie.load
    end
    

    Create one file in the app folder with .env name Add your credentials in this .env file like below

    DB_USERNAME: username
    DB_PASSWORD: password
    

    Use this env variable in the appropriate place like below. in the database.yml

    default: &default
      adapter: postgresql
      encoding: unicode
      pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
      host: localhost
      username: <%= ENV['DB_USERNAME'] %>
      password: <%= ENV['DB_PASSWORD'] %>
    

    Now your ENV variable setup is done. you can check it from the rails console like below.

    rails c
    > ENV["DB_USERNAME"]
    > username
    >ENV["DB_PASSWORD"]
    > password