如何在 Rails 中使用不同的环境变量值? [英] How do I have different envirenment variable values in Rails?

查看:58
本文介绍了如何在 Rails 中使用不同的环境变量值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我如何运行 rails console 命令:

This is how I run rails console command:

COMPANY=b2b RAILS_ENV=development DEPLOY_ENV=localhost rails console

相反,我只想通过在内部设置这些变量来运行 rails console 命令.我该怎么做?

Instead I want to run only rails console command by setting these variables internally. How do I do that?

我看到了一些答案并制作了 config/company.yml 文件:

I saw some answers and made the config/company.yml file:

development:
  COMPANY: b2b
  DEPLOY_ENV: localhost

production:
  COMPANY: b2c
  DEPLOY_ENV: xyz.com

我写了以下 config/initializers/company.rb 文件:

COMPANY_CONFIG = YAML.load_file("#{::Rails.root}/config/company.yml")[::Rails.env]

如何在某些帮助程序/控制器中访问这些变量?我不明白该怎么做?如何在仅运行 rails consolerails server 后设置这些 ENV 变量而不传递上面显示的额外环境变量?

How do I access these variables in some helper/controller? I didn't understand how to do that? How do I set these ENV variables after running only rails console or rails server without passing the extra environment variable shown above?

推荐答案

你不能在 yaml 文件中设置环境变量这个不同的东西.使用 dotenv gem 管理环境变量.

You can't set environment variables in yaml file this difference things. Use dotenv gem for manage environment variables.

先阅读环境变量

但是有肮脏的黑客.您可以在加载 rails 时创建 ENV 变量

But have dirty hack. You can create ENV variable when rails loaded

将此代码添加到config/application.rb中的before_configuration:

config.before_configuration do
  env_file = File.join(Rails.root, 'config', 'company.yml') # Find yml file
  YAML.load(File.open(env_file)).each do |key, value|       # Open file
    ENV[key.to_s] = value                                   # Set value to ENV
  end if File.exists?(env_file)                             # If file exists
end

现在您可以在应用程序的任何位置从 yml 文件访问 env 变量.

And now you can access to env variables from yml file anywhere in app.

我没有测试这个,但我认为这个可行.这项工作.

一些信息

这篇关于如何在 Rails 中使用不同的环境变量值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆