Created
November 29, 2011 20:20
-
-
Save nevans/1406295 to your computer and use it in GitHub Desktop.
Maybe a good way to make resque job definition just a tad simpler.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module SugaredResqueJob | |
def self.new(queue, resque=Resque, &perform) | |
Module.new do | |
extend self | |
define_method :queue do queue end | |
define_method :enqueue do |*args| resque.enqueue(self, *args) end | |
define_method :perform do |*args| perform.call( *args) end | |
end | |
end | |
end | |
# for mocking | |
resque = Object.new | |
SimpleJob = SugaredResqueJob.new(:queue_name, resque) do |*args| | |
"performing on *args: #{args.inspect}" | |
end | |
describe SimpleJob do | |
it "should enqueue job with Resque" do | |
resque.should_receive(:enqueue).with(SimpleJob, :arg1, :arg2, :arg3) | |
SimpleJob.enqueue(:arg1, :arg2, :arg3) | |
end | |
it "should assign job to the appropriate queue" do | |
SimpleJob.queue.should == :queue_name | |
end | |
it "should assign job with the appropriate receiver name" do | |
# "cheating" by using ruby's semi-magical Module#to_s constant lookup | |
SimpleJob.to_s.should == "SimpleJob" | |
end | |
it "should run the appropriate code when performed" do | |
result = SimpleJob.perform(:arg1, :arg2, :arg3) | |
result.should == "performing on *args: [:arg1, :arg2, :arg3]" | |
end | |
end |
DRY resque job creation from 6 lines down to 3: normally my resque job creation looks like a less metaprogrammy version of lines 3..8, but now they would like like lines 14..16.
I like it
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note, I haven't tested this in production... yet. But I really like reducing my Job definitions (which almost always follow this pattern) to three lines of code. If I wanted to include or extend other modules into this, I can: (e.g. for the resque-retry plugin
SimpleJob.extend Resque::Plugins::Retry
should work). Class-inheritance based plugins (e.g. resque-status) simply wouldn't use this (presumably they come with their own sugar).