Skip to content

Commit

Permalink
Added eval jobs as a low ceremony way of declaring jobs without an ex…
Browse files Browse the repository at this point in the history
…plicit class (poor man's block marshalling)
  • Loading branch information
dhh committed Nov 28, 2008
1 parent 4fd41a9 commit 89c3a0b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 6 deletions.
33 changes: 27 additions & 6 deletions lib/delayed/job.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)

This comment has been minimized.

Copy link
@judofyr

judofyr Nov 30, 2008

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

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)
Expand Down Expand Up @@ -254,4 +265,14 @@ def before_save
end

end
end

class EvaledJob
def initialize
@job = yield
end

def perform
eval(@job)
end
end
end
13 changes: 13 additions & 0 deletions spec/job_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down

2 comments on commit 89c3a0b

@tobi
Copy link
Owner

@tobi tobi commented on 89c3a0b Nov 30, 2008

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@trevorturk
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.