如何在Rails控制台中加载环境变量?

时间:2021-07-23 11:53:57

I think this is a little, easy question!

我认为这是一个简单易行的问题!

I'm using .env file to keep all my environment variables, and i'm using foreman.

我正在使用.env文件来保存我的所有环境变量,而我正在使用工头。

Unfortunately, these environment variables are not being loaded when running rails console rails c so, i'm now loading them manually after running the console, which is not the best way.

不幸的是,在运行rails console rails时没有加载这些环境变量因此,我现在正在运行控制台后手动加载它们,这不是最好的方法。

I'd like to know if there any better way for that.

我想知道是否有更好的方法。

3 个解决方案

#1


63  

About a year ago, the "run" command was added to foreman

大约一年前,“跑”命令被添加到工头

ref: https://github.com/ddollar/foreman/pull/121

参考:https://github.com/ddollar/foreman/pull/121

You can use it as follow:

您可以按如下方式使用它:

foreman run rails console

工头运行rails控制台

or

要么

foreman run rake db:migrate

工头运行rake db:migrate

#2


2  

rails does not know about the environmental variables specified in .env file as it is specific to foreman. You need to set the environment explicitly before invoking rails console. Have a look at this question.

rails不知道.env文件中指定的环境变量,因为它特定于foreman。您需要在调用rails console之前显式设置环境。看看这个问题。

#3


0  

I personnaly use dotenv in development and testing environements. With this approach, you don't have to prefix your commands, just call the initializer in your config/application.rb :

我个人在开发和测试环境中使用dotenv。使用这种方法,您不必为命令添加前缀,只需在config / application.rb中调用初始化程序:

Bundler.require(*Rails.groups)

Dotenv::Railtie.load

HOSTNAME = ENV['HOSTNAME']

#1


63  

About a year ago, the "run" command was added to foreman

大约一年前,“跑”命令被添加到工头

ref: https://github.com/ddollar/foreman/pull/121

参考:https://github.com/ddollar/foreman/pull/121

You can use it as follow:

您可以按如下方式使用它:

foreman run rails console

工头运行rails控制台

or

要么

foreman run rake db:migrate

工头运行rake db:migrate

#2


2  

rails does not know about the environmental variables specified in .env file as it is specific to foreman. You need to set the environment explicitly before invoking rails console. Have a look at this question.

rails不知道.env文件中指定的环境变量,因为它特定于foreman。您需要在调用rails console之前显式设置环境。看看这个问题。

#3


0  

I personnaly use dotenv in development and testing environements. With this approach, you don't have to prefix your commands, just call the initializer in your config/application.rb :

我个人在开发和测试环境中使用dotenv。使用这种方法,您不必为命令添加前缀,只需在config / application.rb中调用初始化程序:

Bundler.require(*Rails.groups)

Dotenv::Railtie.load

HOSTNAME = ENV['HOSTNAME']