Permalink
Browse files

Add support for worker middleware modules.

  • Loading branch information...
1 parent 28af75f commit 351a84315c8f0462204f3163652cdda364ba5861 @myronmarston myronmarston committed May 21, 2012
Showing with 52 additions and 1 deletion.
  1. +28 −0 README.md
  2. +10 −1 lib/qless/worker.rb
  3. +14 −0 spec/unit/worker_spec.rb
View
28 README.md
@@ -197,6 +197,34 @@ The following signals are supported:
You should send these to the master process, not the child.
+Workers also support middleware modules that can be used to inject
+logic before, after or around the processing of a single job in
+the child process. This can be useful, for example, when you need to
+re-establish a connection to your database in each job.
+
+Define a module with an `around_perform` method that yields where you
+want the job to be processed:
+
+``` ruby
+module ReEstablishDBConnection
+ def around_perform(job)
+ MyORM.establish_connection
+ yield
+ end
+end
+```
+
+Then, mix-it into the worker class. You can mix-in as many
+middleware modules as you like:
+
+``` ruby
+require 'qless/worker'
+Qless::Worker.class_eval do
+ include ReEstablishDBConnection
+ include SomeOtherAwesomeMiddleware
@ryanlecompte
ryanlecompte May 21, 2012

I'm not seeing how including multiple middleware modules would ensure that they all get invoked. In worker.rb it seems like only the most recently included module would get invoked. Am I missing something?

@myronmarston
myronmarston May 21, 2012

Nope, you're absolutely right. Not sure what I was thinking. I just pushed a fix:

b5d62c2

+end
+```
+
Web Interface
=============
View
11 lib/qless/worker.rb
@@ -70,7 +70,7 @@ def work(interval = 5.0)
else
# We're in the child process
procline "Processing #{job.description}"
- perform(job)
+ around_perform(job) { perform(job) }
exit!
end
end
@@ -114,6 +114,15 @@ def unpause_processing
private
+ # Allow middleware modules to be mixed in and override the
+ # definition of around_perform while providing a default
+ # implementation so our code can assume the method is present.
+ include Module.new {
+ def around_perform(job)
+ yield
+ end
+ }
+
def fail_job(job, error)
group = "#{job.klass}:#{error.class}"
message = "#{error.message}\n\n#{error.backtrace.join("\n")}"
View
14 spec/unit/worker_spec.rb
@@ -78,6 +78,20 @@ def self.perform(job)
File.read(output_file).should include("done")
end
+ it 'supports middleware modules' do
+ worker.extend Module.new {
+ def around_perform(job)
+ File.open(job['file'] + '.before', 'w') { |f| f.write("before") }
+ yield
+ File.open(job['file'] + '.after', 'w') { |f| f.write("after") }
+ end
+ }
+
+ worker.work(0)
+ File.read(output_file + '.before').should eq("before")
+ File.read(output_file + '.after').should eq("after")
+ end
+
it 'begins with a "starting" procline' do
starting_procline = nil
reserver.stub(:reserve) do

0 comments on commit 351a843

Please sign in to comment.