Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Added eval jobs as a low ceremony way of declaring jobs without an ex…

…plicit class (poor man's block marshalling)
  • Loading branch information...
commit 89c3a0b77470c0f8510d3c7a51a36cd07747d9a9 1 parent 4fd41a9
@dhh dhh authored
Showing with 40 additions and 6 deletions.
  1. +27 −6 lib/delayed/job.rb
  2. +13 −0 spec/job_spec.rb
View
33 lib/delayed/job.rb
@@ -76,12 +76,23 @@ def reschedule(message, backtrace = [], time = nil)
end
end
- def self.enqueue(object, priority = 0, run_at = nil)
- unless object.respond_to?(:perform)
- raise ArgumentError, 'Cannot enqueue items which do not respond to perform'
- end
+ def self.enqueue(*args, &block)
+ if block_given?
+ priority = args.first || 0
+ run_at = args.second
+
+ Job.create(:payload_object => EvaledJob.new(&block), :priority => priority.to_i, :run_at => run_at)
@judofyr
judofyr added a note

Any reason why you didn’t wrote object = EvaledJob.new(&block) and put the other Job.create outside the if?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+ else
+ object = args.first
+ priority = args.second || 0
+ run_at = args.third
+
+ unless object.respond_to?(:perform)
+ raise ArgumentError, 'Cannot enqueue items which do not respond to perform'
+ end
- Job.create(:payload_object => object, :priority => priority.to_i, :run_at => run_at)
+ Job.create(:payload_object => object, :priority => priority.to_i, :run_at => run_at)
+ end
end
def self.find_available(limit = 5, max_run_time = MAX_RUN_TIME)
@@ -254,4 +265,14 @@ def before_save
end
end
-end
+
+ class EvaledJob
+ def initialize
+ @job = yield
+ end
+
+ def perform
+ eval(@job)
+ end
+ end
+end
View
13 spec/job_spec.rb
@@ -71,6 +71,19 @@ def perform; @@runs += 1; end
end
+ it "should work with eval jobs" do
+ $eval_job_ran = false
+
+ Delayed::Job.enqueue do <<-JOB
+ $eval_job_ran = true
+ JOB
+ end
+
+ Delayed::Job.work_off
+
+ $eval_job_ran.should == true
+ end
+
it "should work with jobs in modules" do
M::ModuleJob.runs.should == 0

2 comments on commit 89c3a0b

@tobi
Owner

You are welcome to submit that as a changeset :-)

@trevorturk

FYI – I believe this commit makes delayed_job incompatible with Rails < 2.2 because of the Array.first and friends. I fixed it by adding in the same core extensions that were introduced to Rails with this commit:

http://github.com/rails/rails/commit/22af62

I’ll make a note in the wiki that explains the workaround for others who might run into this issue.

Please sign in to comment.
Something went wrong with that request. Please try again.