Resque tasks, worker, web, GenericJob setup for Rails

Usage

resque-web
QUEUE='*' COUNT=3 rake resque:workers &

GenericJob.publish(Product, :reindex_all, :args=> [{:limit=>1000}]

Setup

#append to Rakefile
require 'resque/tasks'
namespace :resque do
  task :setup => :environment
end

class GenericJob
  @queue = :generic

  def self.perform(klass, method, options={})
    options = options.with_indifferent_access
    if options.has_key?(:args)
      klass.constantize.send(method, *options[:args])
    else
      klass.constantize.send(method)
    end
  end

  def self.publish(klass, method, options={})
    Resque.enqueue(self, klass.to_s, method.to_s, options)
  end
end


If you plan to process instances of AR with this setup, be sure to add serialize_ar / deserialize_ar from solving background processing with a single generic background-job

Ruby True / False Comparison / sort with <=>

Using the Spaceship operator with TrueClass / FalseClass is not possible normally:

NoMethodError: undefined method '<=>' for true:TrueClass

But we can change this…

Code

module TrueFalseComparison
  def <=>(other)
    raise ArgumentError unless [TrueClass, FalseClass].include?(other.class)
    other ? (self ? 0 : -1) : (self ? 1 : 0)
  end
end

TrueClass.send(:include, TrueFalseComparison)
FalseClass.send(:include, TrueFalseComparison)

Usage

(true <=> false) == 1
(false <=> true) == -1
[true,false,true].sort == [false,true,true]
[true,'x'].sort -> ArgumentError

Open-uri without ssl / https verification

Usage

require 'open-uri'
require 'openssl'
OpenURI.without_ssl_verification do
  open('https://foo').read
end

Code

module OpenURI
  def self.without_ssl_verification
    old = ::OpenSSL::SSL::VERIFY_PEER
    silence_warnings{ ::OpenSSL::SSL.const_set :VERIFY_PEER, OpenSSL::SSL::VERIFY_NONE }
    yield
  ensure
    silence_warnings{ ::OpenSSL::SSL.const_set :VERIFY_PEER, old }
  end
end

If you are not in Rails you may need silence_warnings

Kill process in capistrano without pkill

Pkill has issues with capistrano, because the pkill command is always inside a capistrano command, thereby matching and killing itself.

pkill free solution

task :foo do
  kill_processes_matching "MaintenanceDaemon"
end

def kill_processes_matching(name)
  run "ps -ef | grep #{name} | grep -v grep | awk '{print $2}' | xargs kill || echo 'no process with name #{name} found'"
end