13

このコマンドは私の問題です:

/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」を使用します。これは、スクリプト/ランナーの引数である必要があります。
これはいくつかの括弧を使用して解決できると思いますが、アイデアはありません。

ソリューションが 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
4

3 に答える 3

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

Rakeタスクに引数を渡すことも可能です。

于 2012-09-14T06:30:36.717 に答える
5

これが古いRailsでscript/runner機能するかどうかはわかりませんが、新しいRailsではrequire 'config/environment'、アプリが読み込まれるため、古いRailsを使用していると思います。次に、そこにスクリプトを書くことができます。

たとえば、引数を取り、提供されている場合はそれを出力してから、アプリ内のユーザー数を出力するスクリプトがあります。

ファイル: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

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
于 2012-09-14T07:09:55.030 に答える