Skip to content

Instantly share code, notes, and snippets.

@ryanong
Created November 16, 2020 16:08
Show Gist options
  • Save ryanong/863505ccb0e755c09e579108a155d5c9 to your computer and use it in GitHub Desktop.
Save ryanong/863505ccb0e755c09e579108a155d5c9 to your computer and use it in GitHub Desktop.
Service Class
require "active_job/arguments"
module Service
extend ActiveSupport::Concern
class ServiceJob
include Sidekiq::Worker
sidekiq_options queue: :web_default
class_attribute :service_class
def perform(*args)
args = ActiveJob::Arguments.deserialize(args)
self.class.service_class.call(*args)
end
end
included do
self::Job = Class.new(ServiceJob)
self::Job.service_class = self
self::Error = Class.new(StandardError)
end
module ClassMethods
def call(*args)
service = new(*args)
if service.runnable?
service.call
end
end
def enqueue(*args)
service = new(*args)
if service.runnable?
args = ActiveJob::Arguments.serialize(args)
self::Job.perform_async(*args)
end
end
def enqueue_at(time, *args)
service = new(*args)
if service.runnable?
args = ActiveJob::Arguments.serialize(args)
self::Job.perform_at(time, *args)
end
end
end
def runnable?
true
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment