Skip to content

Commit

Permalink
Added a before_enqueue hook.
Browse files Browse the repository at this point in the history
  • Loading branch information
jhuckabee authored and defunkt committed Jul 14, 2011
1 parent 40f8b45 commit aa24424
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 0 deletions.
3 changes: 3 additions & 0 deletions docs/HOOKS.md
Expand Up @@ -66,6 +66,9 @@ An unnamed hook (`before_perform`) will be executed first.

The available hooks are:

* `before _enqueue`: Called with the job args before a job is placed on the queue.
If the hook returns `false`, the job will not be placed on the queue.

* `after_enqueue`: Called with the job args after a job is placed on the queue.
Any exception raised propagates up to the code which queued the job.

Expand Down
6 changes: 6 additions & 0 deletions lib/resque.rb
Expand Up @@ -224,6 +224,12 @@ def watch_queue(queue)
#
# This method is considered part of the `stable` API.
def enqueue(klass, *args)
# Perform before_enqueue hooks. Don't perform enqueue if any hook returns false
before_hooks = Plugin.before_enqueue_hooks(klass).collect do |hook|
klass.send(hook, *args)
end
return if before_hooks.any? { |result| result == false }

Job.create(queue_from_class(klass), klass, *args)

Plugin.after_enqueue_hooks(klass).each do |hook|
Expand Down
5 changes: 5 additions & 0 deletions lib/resque/plugin.rb
Expand Up @@ -47,5 +47,10 @@ def failure_hooks(job)
def after_enqueue_hooks(job)
job.methods.grep(/^after_enqueue/).sort
end

# Given an object, returns a list `before_enqueue` hook names.
def before_enqueue_hooks(job)
job.methods.grep(/^before_enqueue/).sort
end
end
end
40 changes: 40 additions & 0 deletions test/job_hooks_test.rb
Expand Up @@ -250,6 +250,46 @@ def self.perform(history)
end
end


context "Resque::Job before_enqueue" do
include PerformJob

class ::BeforeEnqueueJob
@queue = :jobs
def self.before_enqueue_record_history(history)
history << :before_enqueue
end

def self.perform(history)
end
end

class ::BeforeEnqueueJobAbort
@queue = :jobs
def self.before_enqueue_abort(history)
false
end

def self.perform(history)
end
end

test "the before enqueue hook should run" do
history = []
@worker = Resque::Worker.new(:jobs)
Resque.enqueue(BeforeEnqueueJob, history)
@worker.work(0)
assert_equal history, [:before_enqueue], "before_enqueue was not run"
end

test "a before enqueue hook that returns false should prevent the job from getting queued" do
history = []
@worker = Resque::Worker.new(:jobs)
Resque.enqueue(BeforeEnqueueJobAbort, history)
assert_equal 0, Resque.size(:jobs)
end
end

context "Resque::Job all hooks" do
include PerformJob

Expand Down

0 comments on commit aa24424

Please sign in to comment.