Load environment variable in boot file

2k views Asked by At

I am facing issue while loading envrionment variable in boot.rb. I tried with 2 gems dotenv & dotenv-rails but none of them worked for me. Other places I am able to use environment variable but not in boot.rb. Anyone have any clue on this one

if ["development"].include?(ENV['RAILS_ENV'])
   require 'bootsnap/setup'
   
   Bootsnap.setup(
    cache_dir:            'tmp/cache',          # Path to your cache
    development_mode:     'development', # Current working environment, e.g. RACK_ENV, RAILS_ENV, etc
    load_path_cache:      true,                 # Optimize the LOAD_PATH with a cache
    autoload_paths_cache: true,                 # Optimize ActiveSupport autoloads with cache
    compile_cache_iseq:   true,                 # Compile Ruby code into ISeq cache, breaks coverage reporting.
    compile_cache_yaml:   true                  # Compile YAML into a cache
  )
end
2

There are 2 answers

2
max On BEST ANSWER

DotEnv will only load your .env file into env once the Gem has been loaded.

In Rails this is done by the line Bundler.require(*Rails.groups) in config/application.rb. If you need to access the env vars before that you need to manually call Dotenv::Railtie.load:

Bundler.require(*Rails.groups)
Dotenv::Railtie.load

Or at least thats what the readme would lead you to belive. Instead of the Railtie I guess you could use the plain ruby approach:

require 'dotenv'
Dotenv.load 

But there are tons options to set ENV vars from a file such as direnv which is not a Ruby gem and hooks into your shell itself.

0
user1934428 On

You could use - depending on your needs - a load or require to explicitly process your .env file, before testing the environment variable.