如何在Rails中的相同环境中通过域智能加载ENV变量?

时间:2016-11-17 07:27:03

标签: ruby-on-rails ruby-on-rails-4 devise

我使用了Devise,omniauth-facebook gem。

我需要在同一个应用程序中为同一环境(如生产)中的不同主机加载不同的ENV变量。需要实施Login with facebook

我有两个主机用于相同的应用程序代码:

1)www.abc-domain.com

2)www.xyz-domian.com

我的ENV变量(config / settings.yml):

production:
  abc-domain-credential:
    facebook_access_key: "ABC_ACCESS_KEY"
    facebook_api_key: "ABC_API_KEY"
  xyz-domain-credential:
    facebook_access_key: "XYZ_ACCESS_KEY"
    facebook_api_key: "XYZ_API_KEY"

在我的devise.rb文件(config / initializer / devise.rb)中:

Devise.setup do |config|
  ...
  ...
  require "omniauth-facebook"
  config.omniauth :facebook, ENV_SETTINGS["abc-domain-credential"]["facebook_access_key"], ENV_SETTINGS["abc-domain-credential"]["facebook_api_key"], scope: 'email', info_fields: 'email,name'
  # ===== OR ======
  config.omniauth :facebook, ENV_SETTINGS["xyz-domain-credential"]["facebook_access_key"], ENV_SETTINGS["xyz-domain-credential"]["facebook_api_key"], scope: 'email', info_fields: 'email,name'
  ...
  ...
end

当我访问http://www.abc-domain.com时,下面的env应该从settings.yml

加载
abc-domain-credential:
   facebook_access_key: "ABC_ACCESS_KEY"
   facebook_api_key: "ABC_API_KEY"

当我访问http://www.xyz-domain.com时,下面的env应该从settings.yml

加载
xyz-domain-credential:
  facebook_access_key: "XYZ_ACCESS_KEY"
  facebook_api_key: "XYZ_API_KEY"

使用Facebook登录按钮:

<%= link_to "/users/auth/facebook", "Login With Facebook" %>

我必须为两个主机加载不同的ENV变量,如

if host == "abc-domain"
  config.omniauth :facebook, ENV_SETTINGS["abc-domain-credential"]["facebook_access_key"], ENV_SETTINGS["abc-domain-credential"]["facebook_api_key"], scope: 'email', info_fields: 'email,name'
elsif host == "xyz-domain"
  config.omniauth :facebook, ENV_SETTINGS["xyz-domain-credential"]["facebook_access_key"], ENV_SETTINGS["xyz-domain-credential"]["facebook_api_key"], scope: 'email', info_fields: 'email,name'
end
<{1>}文件中的

1 个答案:

答案 0 :(得分:0)

将两个凭据上传到不同的密钥(正如您所做)并使用

request.base_url

在您的Devise控制器中确定调用域并使用正确的凭据。