#!/usr/bin/env ruby # # == Synopsis # # This is a replacement for script/runner which avoids loading up the # rails environment and instead queues things for async_observer to # do. Note that, unlike script/runner, a filename is not accepted; you # must provide the code to run on the command-line. # # == Usage # # beanstalk-queue [OPTION] ... 'CODE' # # -d DELAY: # amount of delay before the job is run (default 0 seconds) # # -e ENVIRONMENT: # set the rails environment (falls back to ENV['RAILS_ENV'] or # 'development' if unset) # # -p PRIORITY: # set the job priority (default 65536) # # -t TTR: # set the job's time to run (default 120 seconds) # # -v, --verbose: # be verbose # # -h, --help: # display this help # # CODE: the ruby code to be called asynchronously # require 'rubygems' require 'beanstalk-client' require 'getoptlong' require 'rdoc/usage' require 'yaml' RAILS_ROOT = File.expand_path(File.join(File.dirname(__FILE__), "..")) opts = GetoptLong.new( ['--help', '-h', GetoptLong::NO_ARGUMENT], ['-d', GetoptLong::REQUIRED_ARGUMENT], ['-e', GetoptLong::REQUIRED_ARGUMENT], ['-p', GetoptLong::REQUIRED_ARGUMENT], ['-t', GetoptLong::REQUIRED_ARGUMENT], ['--verbose', '-v', GetoptLong::NO_ARGUMENT] ) pool = Beanstalk::Pool.new(%w(localhost:11300)) tube = 'default' delay = 0 environment = ENV['RAILS_ENV'] || 'development' priority = 65536 ttr = 120 verbose = false opts.each do |opt,arg| case opt when '--help' RDoc::usage when '-d' delay = arg.to_i when '-e' environment = arg when '-p' priority = arg.to_i when '-t' ttr = arg.to_i when '--verbose' verbose = true end end if ARGV.length != 1 $stderr.puts "missing code to run (try #{File.basename(__FILE__)} --help)\n" exit 1 end code = ARGV[0] case environment when 'production' if File.exist?(File.join(RAILS_ROOT, "REVISION")) tube = File.read(File.join(RAILS_ROOT, "REVISION")).strip end when 'development' tube = 'ourproj-development' end puts "using tube #{tube}" if verbose pool.connect pool.use(tube) job = YAML.dump({:type => :rails, :code => code}) puts "job:", job if verbose job_id = pool.put(job, priority, delay, ttr) puts "job #{job_id} sent to #{pool.last_server}" if verbose