如何使用dotenv在rails应用程序上添加环境变量到ruby?

时间:2015-01-21 08:56:45

标签: ruby-on-rails ruby environment-variables production-environment

我想设置SECRET_KEY_BASE中使用的secrets.yml

production:
  secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>

我尝试在.profile中添加以下代码:

export SECRET_KEY_BASE=cfbc3b45d65db30b853cdc0557e0be85609cf75974ebb706f46a00abe09eee9454b3d311e48ee4157e1e5d5e3de5b8d2a329dff13871837cbaeae6af2bc2e42f

它运行良好,但仍然没有那么好,我知道dotenv可以在app的根路径中的.env文件中添加它,所以我添加

gem 'dotenv-rails'
gem 'dotenv-deployment'

然后我将以下代码添加到rails app的根路径中的.env.production

SECRET_KEY_BASE=cfbc3b45d65db30b853cdc0557e0be85609cf75974ebb706f46a00abe09eee9454b3d311e48ee4157e1e5d5e3de5b8d2a329dff13871837cbaeae6af2bc2e42f

但为什么这不起作用?

1 个答案:

答案 0 :(得分:2)

在Rails 4.1中,config / secrets.yml是应用程序的secret_key_base的新默认位置。但是,它也可以用于存储其他秘密变量,使其成为特定于环境的令牌,API密钥等的好地方。

使用您要存储的机密填写文件,例如:

development:
  secret_key_base: your_development_secret
  api_key: some_key
production:
  secret_key_base: your_production_secret
  twitter_consumer_key: production_twitter_key
  twitter_consumer_secret: production_twitter_secret
  twitter_oauth_token: production_oauth_token
  twitter_oauth_token_secret: production_oauth_secret

在您的代码中,您可以使用Rails.application.secrets:

访问这些秘密
Twitter.configure do |config|
  config.consumer_key       = Rails.application.secrets.twitter_consumer_key
  config.consumer_secret    = Rails.application.secrets.twitter_consumer_secret
  config.oauth_token        = Rails.application.secrets.twitter_oauth_token
  config.oauth_token_secret = Rails.application.secrets.twitter_oauth_token_secret
end

默认情况下,secrets.yml会被检入git,并将其添加到你的.gitignore文件中。