使用一些参数运行rails runner

时间:2012-09-14 06:18:27

标签: ruby-on-rails ruby linux bash command-line

这个命令是我的问题:

/usr/local/bin/ruby **script/runner** --environment=production app/jobs/**my_job.rb** -t my_arg

`my_job.rb` is my script, which handles command line arguments. In this case it is `-t my_arg`.

my_job.rb也将`--environment = production'作为参数,这应该是script / runner的参数。
我想这可以用一些括号来解决,但没有想法。

如果解决方案没有触及(或依赖于)Rails或Linux的全球环境,那就更好了。

/usr/local/lib/ruby/1.8/optparse.rb:1450:in `complete': invalid option: --environment=production (OptionParser::InvalidOption)
  from /usr/local/lib/ruby/1.8/optparse.rb:1448:in `catch'
  from /usr/local/lib/ruby/1.8/optparse.rb:1448:in `complete'
  from /usr/local/lib/ruby/1.8/optparse.rb:1261:in `parse_in_order'
  from /usr/local/lib/ruby/1.8/optparse.rb:1254:in `catch'
  from /usr/local/lib/ruby/1.8/optparse.rb:1254:in `parse_in_order'
  from /usr/local/lib/ruby/1.8/optparse.rb:1248:in `order!'
  from /usr/local/lib/ruby/1.8/optparse.rb:1339:in `permute!'
  from /usr/local/lib/ruby/1.8/optparse.rb:1360:in `parse!'
  from app/jobs/2new_error_log_rt_report.rb:12:in `execute'
  from app/jobs/2new_error_log_rt_report.rb:102
  from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `eval'
  from /home/www/maldive/admin/releases/20120914030956/vendor/rails/railties/lib/commands/runner.rb:46
  from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
  from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
  from script/runner:3

2 个答案:

答案 0 :(得分:7)

script/runner不会获取文件的路径,而是需要执行一些Ruby:

script/runner "MyClass.do_something('my_arg')"

您始终可以使用环境变量设置Rails环境,例如:

RAILS_ENV=production script/runner "MyClass.do_something('my_arg')"

如果您想运行一些复杂的任务,最好将其作为Rake任务编写。例如,您可以创建文件lib/tasks/foo.rake

namespace :foo do
  desc 'Here is a description of my task'
  task :bar => :environment do
    # Your code here
  end
end

您可以执行以下操作:

rake foo:bar

script/runner一样,您可以使用环境变量设置环境:

RAILS_ENV=production rake foo:bar

也可以pass arguments to a Rake task

答案 1 :(得分:4)

我假设您使用的是基于script/runner的旧版Rails,我不知道这是否适用于较旧的Rails,但是在较新的Rails中,您只能require 'config/environment',而它将加载该应用程序。然后你可以在那里编写脚本。

例如,我有一个接受参数的脚本,如果提供了参数,则将其打印出来,然后打印出我的应用中有多少用户:

文件:app / jobs / my_job.rb

require 'optparse'

parser = OptionParser.new do |options|
  options.on '-t', '--the-arg SOME_ARG', 'Shows that we can take an arg' do |arg|
    puts "THE ARGUMENT WAS #{arg.inspect}"
  end
end

parser.parse! ARGV

require_relative '../../config/environment'

puts "THERE ARE #{User.count} USERS" # I have a users model

没有args调用:

$ be ruby app/jobs/my_job.rb 
THERE ARE 2 USERS

使用arg简写调用:

$ be ruby app/jobs/my_job.rb -t my_arg
THE ARGUMENT WAS "my_arg"
THERE ARE 2 USERS

用arg长手打电话:

$ be ruby app/jobs/my_job.rb --the-arg my_arg
THE ARGUMENT WAS "my_arg"
THERE ARE 2 USERS
相关问题