2012-09-14 55 views
9

这个命令是我的问题:运行轨道亚军一些参数

/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`. 

​​也需要`--environment =生产”作为它的参数,它应该是脚本/亚军的说法。
我想这可以使用一些括号解决,但没有一个想法。

如果解不接触(或依赖)的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 

回答

5

script/runner并不需要一个文件路径,而是需要一些红宝石,它会执行:

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

4

我假设你在基于script/runner旧的Rails的,我不知道这是否适用于旧的Rails的或没有,但在新的Rails,你可以require 'config/environment',它会载入应用程式。然后你可以在那里写你的脚本。

例如,我有一个脚本,需要一个参数,打印出来,如果有人提供,然后打印出有多少用户在我的应用程序:

文件:应用程序/工作/ 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 

与无参数调用:

$ 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