Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Merge pull request #18260 from isaacseymour/active-job-delegate-deser…
…ialize

ActiveJob: delegate deserialization to the job class
  • Loading branch information
dhh committed Dec 30, 2014
2 parents 4080dd2 + 65542e2 commit a4d5e83
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 4 deletions.
25 changes: 25 additions & 0 deletions activejob/CHANGELOG.md
@@ -1 +1,26 @@
* `ActiveJob::Base.deserialize` delegates to the job class

Since `ActiveJob::Base#deserialize` can be overriden by subclasses (like `ActiveJob::Base#serialize`)
this allows jobs to attach arbitrary metadata when they get serialized and read it back when they get
performed. E.g.

class DeliverWebhookJob < ActiveJob::Base
def serialize
super.merge('attempt_number' => (@attempt_number || 0) + 1)
end

def deserialize(job_data)
super(job_data)
@attempt_number = job_data['attempt_number']
end

rescue_from(TimeoutError) do |ex|
raise ex if @attempt_number > 5
retry_job(wait: 10)
end
end

*Isaac Seymour*


Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/activejob/CHANGELOG.md) for previous changes.
32 changes: 28 additions & 4 deletions activejob/lib/active_job/core.rb
Expand Up @@ -22,10 +22,8 @@ module Core
module ClassMethods
# Creates a new job instance from a hash created with +serialize+
def deserialize(job_data)
job = job_data['job_class'].constantize.new
job.job_id = job_data['job_id']
job.queue_name = job_data['queue_name']
job.serialized_arguments = job_data['arguments']
job = job_data['job_class'].constantize.new
job.deserialize(job_data)
job
end

Expand Down Expand Up @@ -69,6 +67,32 @@ def serialize
}
end

# Attaches the stored job data to the current instance. Receives a hash
# returned from +serialize+
#
# ==== Examples
#
# class DeliverWebhookJob < ActiveJob::Base
# def serialize
# super.merge('attempt_number' => (@attempt_number || 0) + 1)
# end
#
# def deserialize(job_data)
# super(job_data)
# @attempt_number = job_data['attempt_number']
# end
#
# rescue_from(TimeoutError) do |ex|
# raise ex if @attempt_number > 5
# retry_job(wait: 10)
# end
# end
def deserialize(job_data)
self.job_id = job_data['job_id']
self.queue_name = job_data['queue_name']
self.serialized_arguments = job_data['arguments']
end

private
def deserialize_arguments_if_needed
if defined?(@serialized_arguments) && @serialized_arguments.present?
Expand Down

0 comments on commit a4d5e83

Please sign in to comment.