public
Created

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
# app/models/queue/base.rb
class Queue::Base
class << self
def enqueue(object, method, *args)
meta = { 'method' => method }
ensure_queueable!(object, method, *args)
if is_model?(object)
Resque.enqueue(self, meta.merge('class' => object.class.name, 'id' => object.id), *args)
else
Resque.enqueue(self, meta.merge('class' => object.name), *args)
end
end
 
def perform(meta = { }, *args)
if meta.has_key?('id')
if model = meta['class'].constantize.find_by_id(meta['id'])
model.send(meta['method'], *args)
end
else
meta['class'].constantize.send(meta['method'], *args)
end
end
def is_model?(object)
object.class.respond_to?(:find_by_id)
end
private
def ensure_queueable!(object, method, *args)
ensure_responds_to!(object, method)
ensure_arity!(object, method, args.length)
end
 
def ensure_responds_to!(object, method)
unless object.respond_to?(method)
raise "object must respond to #{method}"
end
end
def ensure_arity!(object, method, arity)
required = object.method(method).arity
if required < 0 && arity < -required
raise "#{method}: #{arity} of #{-required} arguments given"
elsif required >= 0 && required != arity
raise "#{method}: #{arity} of #{required} arguments given"
end
end
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.