Class: Utilisable::BackgroundService

Inherits:
Service
  • Object
show all
Defined in:
lib/utilisable/background_service.rb

Overview

Simple interface for running background jobs as commands. Meant to be inherited like this: class SidekiqService < Utilisable::BackgroundService

def initialize(options)
  super(options, ServiceObjectWorker)
end

end

Needs a worker to work, that should look like this: class ServiceObjectWorker

include Sidekiq::Worker
sidekiq_options queue: :default, retry: true

def perform(klass, *args)
  klass.constantize.call(args)
end

end

Now you can create a command like this: class SimpleService < SidekiqService

attr_reader :foo

def initialize(foo, options = {})
  super(options)
  @foo = foo
end

private

def perform
  puts foo
end

end

And invoke it like this: SimpleService.call(foo, background: true, perform_in: 15.minutes)

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Service

#broadcast, call, #local_registrations, #on, #transaction

Constructor Details

#initialize(options, worker_class) ⇒ BackgroundService

Returns a new instance of BackgroundService.


45
46
47
48
# File 'lib/utilisable/background_service.rb', line 45

def initialize(options, worker_class)
  @options = options
  @worker_class = worker_class
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options


43
44
45
# File 'lib/utilisable/background_service.rb', line 43

def options
  @options
end

#worker_classObject (readonly)

Returns the value of attribute worker_class


43
44
45
# File 'lib/utilisable/background_service.rb', line 43

def worker_class
  @worker_class
end

Instance Method Details

#callObject


50
51
52
53
54
# File 'lib/utilisable/background_service.rb', line 50

def call
  return broadcast(:fail) unless valid?

  background? ? setup_worker : perform
end