Skip to content

Commit ee4b700

Browse files
committed
add the job hooks api
1 parent 9d973af commit ee4b700

File tree

1 file changed

+45
-1
lines changed

1 file changed

+45
-1
lines changed

lib/resque/job.rb

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@ class Job
1515
include Helpers
1616
extend Helpers
1717

18+
# Raise Resque::Job::DontPerform from a before_perform hook to
19+
# abort the job.
20+
DontPerform = Class.new(StandardError)
21+
1822
# The worker object which is currently processing this job.
1923
attr_accessor :worker
2024

@@ -101,7 +105,47 @@ def self.reserve(queue)
101105
# Calls #perform on the class given in the payload with the
102106
# arguments given in the payload.
103107
def perform
104-
args ? payload_class.perform(*args) : payload_class.perform
108+
job_args = args || []
109+
job_was_performed = false
110+
111+
begin
112+
# Execute before_perform hook. Abort the job gracefully if
113+
# Resque::DontPerform is raised.
114+
begin
115+
if payload_class.respond_to?(:before_perform)
116+
payload_class.before_perform(*job_args)
117+
end
118+
rescue DontPerform
119+
return false
120+
end
121+
122+
# Execute the job. Do it in an around_perform hook if available.
123+
if payload_class.respond_to?(:around_perform)
124+
payload_class.around_perform(*job_args) do
125+
payload_class.perform(*job_args)
126+
job_was_performed = true
127+
end
128+
else
129+
payload_class.perform(*job_args)
130+
job_was_performed = true
131+
end
132+
133+
# Execute after_perform hook
134+
if payload_class.respond_to?(:after_perform)
135+
payload_class.after_perform(*job_args)
136+
end
137+
138+
# Return true if the job was performed
139+
return job_was_performed
140+
141+
# If an exception occurs during the job execution, look for an
142+
# on_failure hook then re-raise.
143+
rescue Object => e
144+
if payload_class.respond_to?(:on_failure)
145+
payload_class.on_failure(e, *job_args)
146+
end
147+
raise
148+
end
105149
end
106150

107151
# Returns the actual class constant represented in this job's payload.

0 commit comments

Comments
 (0)