Skip to content

Instantly share code, notes, and snippets.

@theoretick
Forked from bandito/gist:351550
Created September 14, 2016 17:43
Show Gist options
  • Save theoretick/ad782f602f5d062b3dd2e6b51c67d765 to your computer and use it in GitHub Desktop.
Save theoretick/ad782f602f5d062b3dd2e6b51c67d765 to your computer and use it in GitHub Desktop.
module RQueue
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
#set the queue name some as the model name
def self.extended(klass)
@queue = klass.instance_variable_set("@queue", klass.name.downcase.to_sym)
end
#queue to resque
def queue(meth, *args)
Resque.enqueue(self, meth, *args)
end
#queue methods that start with queue_[actual method name] and [actual method name] exists as a method
def method_missing(method_name, *args)
return queue($1, *args) if method_name.to_s =~ /^queue_(.*?)$/ && respond_to?($1)
super
end
#perform for class methods
def perform(meth, *args)
__send__(meth, *args)
end
#find perform for instance methods
def instance_perform(id, meth, *args)
find(id).__send__(meth, *args)
end
end
#queue instance jobs
#this is somewhat bound to active record objects because it uses the id
def method_missing(method_name, *args)
return self.class.queue(:instance_perform, self.id, $1, *args) if method_name.to_s =~ /^queue_(.*?)$/ && respond_to?($1)
super
end
end
###################
# How to use
###################
class Category < ActiveRecord::Base
include RQueue
def self.cache_counters
.....
end
def calculate_score(limit)
....
end
end
# Somewhere in your controller
class WhateverController < ActionController
def dostuff
#some light stuff
# ....
# heavy computations
@category.queue_calculate_score(3) #Instead of Resque.enqueue(CategoryScoreCalculatorJob, @category.id)
Category.queue_cache_counters #Instead of Resque.enqueue(CategoryCacheCounterJob)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment