Skip to content

Instantly share code, notes, and snippets.

@siannopollo
Created April 4, 2018 22:45
Show Gist options
  • Save siannopollo/cd9b896227551811660507f38b89ea4e to your computer and use it in GitHub Desktop.
Save siannopollo/cd9b896227551811660507f38b89ea4e to your computer and use it in GitHub Desktop.
#delay method for ActiveJob jobs
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
include ApplicationJob::PerformableMethod
end
class ApplicationJob
module PerformableMethod
def delay(options = {})
ApplicationJob::PerformableMethod::Proxy.new self, options
end
class Proxy < Struct.new(:object, :options)
def method_missing(method_name, *args)
job = ApplicationJob::PerformableMethod::Job
job.set options
job.perform_later object, method_name.to_s, *args
end
end
class Job < ApplicationJob
def perform(object, method_name, *args)
object.send method_name, *args
end
end
end
end
@siannopollo
Copy link
Author

I'm using DelayedJob as the queue for ActiveJob in a project, but didn't like how each ActiveRecord object was serialized in a delayed job using the massively long YAML format. Standard ActiveJob jobs will use the GlobalID of the AR object to serialize/deserialize the object, and I wanted something like that for my DelayedJobs.

I also like the convenience of the some_object.delay.do_something syntax that DelayedJob provides, and wanted to keep the syntax without actually keeping the DelayedJob version.

This code is the result, and seems to work. I should probably add some error handling for ActiveJob::DeserializationError errors when the object is no longer in the db.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment