Ruby/Rails 环境变量
jinhucheung opened this issue · comments
rails环境变量
引用环境变量
- 在.rb文件 直接引用
ENV['ENV_NAME']
- 非.rb文件(如.yml等) 使用嵌入ruby,
<%= ENV['ENV_NAME'] %>
设置环境变量
第一种方式
- 直接在shell中设置环境变量 如
export ENV_NAME="Hello World"
- 或者在.bashrc中设置
第二种方式
在rails项目中设置,具体过程
- 创建config/local_env.yml文件,写入
ENV_NAME: "Hello World"
- 在config/application.rb中读取设置变量, 具体代码如下
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
- 将local_env.yml加入.gitignore
/config/local_env.yml
注意 rails设置的环境变量优先于shell 环境变量
第三种方式
使用 Figaro Gem, 其特点是可以针对deveploment/test/production环境来设置不同值的环境变量