bash Ruby on Rails:如何指定运行脚本环境

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/758975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 20:49:17  来源:igfitidea点击:

Ruby on Rails: How can I specify runner script environment

ruby-on-railslinuxbash

提问by Goro

I am using a shell script to run some runner scripts in my Ruby on Rails app. I need to run it on the production database, but the following:

我正在使用 shell 脚本在我的 Ruby on Rails 应用程序中运行一些运行器脚本。我需要在生产数据库上运行它,但如下:

#!/bin/bash
/usr/bin/ruby RAILS_ENV=production ../script/runner ../lib/tasks.rb 

gives an error:

给出一个错误:

/usr/bin/ruby: No such file or directory -- RAILS_ENV=production (LoadError)

I have tried to force it in config/environment.rb

我试图在 config/environment.rb 中强制它

ENV['RAILS_ENV'] ||= 'production'

or even

甚至

ENV['RAILS_ENV'] = 'production'

but even with that it still runs in development environment.

但即便如此,它仍然在开发环境中运行。

Update: I can force the scripts to connect to the right database by editing the config/database.yml file, but I wonder what's the proper way of doing it.

更新:我可以通过编辑 config/database.yml 文件来强制脚本连接到正确的数据库,但我想知道这样做的正确方法是什么。

回答by nitecoder

The help on the command line for script/runner gives you your answer.

script/runner 的命令行帮助为您提供了答案。

script/runner -e production Model.method

回答by Garrett

If that's your command, the order of your arguments is your biggest problem.

如果这是您的命令,那么您的参数顺序是您最大的问题。

/usr/bin/ruby RAILS_ENV=production ../script/runner ../lib/tasks.rb

Is different than.

不同于。

/usr/bin/ruby ../script/runner ../lib/tasks.rb RAILS_ENV=production

The second example is looking for the file, the first one is setting a runtime variable while ruby interpreting it as the file you want to run.

第二个示例是查找文件,第一个示例是设置运行时变量,而 ruby​​ 将其解释为您要运行的文件。

回答by Avery Payne

If you redo your script like this:

如果你像这样重做你的脚本:

#!/bin/bash
RAILS_ENV=production
/usr/bin/ruby ../script/runner ../lib/tasks.rb

...that will make it stick for the lifetime of the script. To make it stick for the lifetime of the shell's session, change it to

...这将使其在脚本的整个生命周期内都保持不变。要使其在 shell 会话的整个生命周期内保持不变,请将其更改为

#!/bin/bash
export RAILS_ENV=production
/usr/bin/ruby ../script/runner ../lib/tasks.rb

回答by shodanex

You can set the environment variable like this :

您可以像这样设置环境变量:

RAILS_ENV=production /usr/bin/ruby ../script/runner ../lib/tasks.rb

回答by gaspar

RAILS_ENV=production script/rails runner 'user = User.find(:first, :conditions => {:admin => true}) ; user.password, user.password_confirmation = "mypasswd"; user.save!'

it worked for me

它对我有用