Is it possible to set ENV variables for rails development environment in my code?

后端 未结 7 1129
心在旅途
心在旅途 2020-11-27 09:59

I know that I can set my ENV variables in bash via

export admin_password = \"secret\"

But is there a way to do it in my rails source code s

相关标签:
7条回答
  • 2020-11-27 10:37

    Script for loading of custom .env file: Add the following lines to /config/environment.rb, between the require line, and the Application.initialize line:

    # Load the app's custom environment variables here, so that they are loaded before environments/*.rb
    
    app_environment_variables = File.join(Rails.root, 'config', 'local_environment.env')
    if File.exists?(app_environment_variables)
      lines = File.readlines(app_environment_variables)
      lines.each do |line|
        line.chomp!
        next if line.empty? or line[0] == '#'
        parts = line.partition '='
        raise "Wrong line: #{line} in #{app_environment_variables}" if parts.last.empty?
        ENV[parts.first] = parts.last
      end
    end
    

    And config/local_environment.env (you will want to .gitignore it) will look like:

    # This is ignored comment
    DATABASE_URL=mysql2://user:psw@0.0.0:3307/database
    RACK_ENV=development
    

    (Based on solution of @user664833)

    0 讨论(0)
提交回复
热议问题