如何在Rails环境中运行Ruby文件?

时间:2012-03-18 09:27:48

标签: ruby-on-rails ruby ruby-on-rails-3

我想在Rails环境的上下文中运行Ruby文件。 rails runner几乎可以做我想做的事,但我想给它一个文件名和参数。我很确定这是可能的,因为我以前做过。有人能提醒我怎么做吗?

4 个答案:

答案 0 :(得分:107)

最简单的方法是使用rails runner,因为您不需要修改脚本。

http://guides.rubyonrails.org/command_line.html#rails-runner

只需说rails runner script.rb

答案 1 :(得分:32)

只需在脚本中输入environment.rb即可。如果您的脚本位于Rails应用程序的script目录中

require File.expand_path('../../config/environment', __FILE__)

您可以通过在运行脚本时设置RAILS_ENV环境变量来控制所使用的环境(开发/测试/生产)。

RAILS_ENV=production ruby script/test.rb

答案 2 :(得分:22)

Runner以非交互方式在Rails的上下文中运行Ruby代码。

来自rails runner命令:

Usage: runner [options] ('Some.ruby(code)' or a filename)

    -e, --environment=name           Specifies the environment for the runner to operate under (test/development/production).
                                     Default: development

    -h, --help                       Show this help message.

你也可以使用runner作为你的脚本的shebang行:

-------------------------------------------------------------
#!/usr/bin/env /Users/me/rails_project/script/rails runner

Product.all.each { |p| p.price *= 2 ; p.save! }
-------------------------------------------------------------

答案 3 :(得分:4)

这是一个老问题,但在我看来,我经常发现创建一个rake任务很有帮助......而且它实际上非常简单。

def params_user params.require(:user).permit(:email, :name, :other_attributes) end

lib/tasks/example.rake

然后在终端运行中:

namespace :example do

desc "Sample description you'd see if you ran: 'rake --tasks' in the terminal"
task create_user: :environment do
  User.create! first_name: "Foo", last_name: "Bar"
end

在本地,这将在您的开发数据库的上下文中运行,如果在Heroku上运行,它将在连接到您的生产数据库时运行。我发现这对于协助迁移或修改表格特别有用。