Created
November 16, 2020 16:08
-
-
Save ryanong/863505ccb0e755c09e579108a155d5c9 to your computer and use it in GitHub Desktop.
Service Class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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