# [Ruby On Rails]將環境變數存在local_env.yml檔中 ###### tags: `Ruby On Rails` url: https://qiita.com/alokrawat050/items/0d7791b3915579f95791 ## 使用方法(以database.yml為例) 新增config/local_env.yml ```yaml POSTGRES_HOST: your_host POSTGRES_DATABASE: your_db POSTGRES_USERNAME: your_username POSTGRES_PASSWORD: your_password ``` <br> 修改config/application.rb ```ruby require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module BlogSimple class Application < Rails::Application #...省略 #----------------加上這段----------------- config.before_configuration do env_file = File.join(Rails.root, 'config', 'local_env.yml') YAML.load(File.open(env_file)).each do |key, value| ENV[key.to_s] = value end if File.exists?(env_file) #----------------加上這段----------------- end end end ``` <br> database.yml ```yaml development: adapter: postgresql host: <%= ENV['POSTGRES_HOST'] %> username: <%= ENV['POSTGRES_USERNAME'] %> password: <%= ENV['POSTGRES_PASSWORD'] %> encoding: unicode port: 5432 database: <%= ENV['POSTGRES_DATABASE'] %> pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> timeout: 5000 ``` <br> .gitignore ```terminal /config/local_env.yml ```