使用一些参数运行Rails runner

28 浏览
0 Comments

使用一些参数运行Rails runner

这是我的问题命令:

/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

admin 更改状态以发布 2023年5月22日
0
0 Comments

我假设你正在使用基于 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

不带参数调用:

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

使用参数缩写调用:

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

使用参数长格式调用:

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

0
0 Comments

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

还可以向 Rake 任务传递参数

0