From 65542e27979fce1f6b0893a00e4d51849616de34 Mon Sep 17 00:00:00 2001 From: Isaac Seymour Date: Tue, 30 Dec 2014 18:26:39 +0000 Subject: ActiveJob: delegate full deserialization to class --- activejob/CHANGELOG.md | 25 +++++++++++++++++++++++++ activejob/lib/active_job/core.rb | 32 ++++++++++++++++++++++++++++---- 2 files changed, 53 insertions(+), 4 deletions(-) (limited to 'activejob') diff --git a/activejob/CHANGELOG.md b/activejob/CHANGELOG.md index f9c481998e..c9d9484518 100644 --- a/activejob/CHANGELOG.md +++ b/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. diff --git a/activejob/lib/active_job/core.rb b/activejob/lib/active_job/core.rb index a0e55a0028..450c56bfdc 100644 --- a/activejob/lib/active_job/core.rb +++ b/activejob/lib/active_job/core.rb @@ -22,10 +22,8 @@ module ActiveJob 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 @@ -69,6 +67,32 @@ module ActiveJob } 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? -- cgit v1.2.3