参考:http://railsapps.github.io/rails-environment-variables.html
整理一下,方法主要有三种:
一.直接设置UNIX环境变量,这个不用讲了吧。
二.使用Figaro Gem
1.$ rails generate figaro:install
2.在config/application.yml中添加想要添加的环境变量
3.在某些环境变量不被允许的场景下可以用:
Figaro.env.gmail_username
4.设置不同开发场景中:
HELLO: world
development:
HELLO: developers
production:
HELLO: users
三.使用本地变量:
1.添加一个本地yml文件
2.确保application.rb中有如下内容:
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
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
3.之后就可在程序中任意地方使用环境变量了。
4.设定使用场景:
if Rails.env.development?
config.action_mailer.smtp_settings = {
user_name: ENV["GMAIL_USERNAME_DEV"]
}
end
if Rails.env.test?
config.action_mailer.smtp_settings = {
user_name: ENV["GMAIL_USERNAME_TEST"]
}
end
if Rails.env.production?
config.action_mailer.smtp_settings = {
user_name: ENV["GMAIL_USERNAME"]
}
end
来源:https://www.cnblogs.com/marvin007/p/3188392.html