Skip to content

Instantly share code, notes, and snippets.

@aghuddleston
Created July 29, 2016 20:25
Show Gist options
  • Save aghuddleston/c3051a563117996a1e659fcef48812d6 to your computer and use it in GitHub Desktop.
Save aghuddleston/c3051a563117996a1e659fcef48812d6 to your computer and use it in GitHub Desktop.
"Command" class to create a simple chain of Sidekiq workers and an example worker implementation.
require 'json'
class AddIndividiualCmd
attr_reader :roster_id, :current_step
STEPS = %w(
PhoneInsertWorker
RosterLinkToSchoolWorker
RosterLinkToSchoolAddressWorker
)
def initialize(roster_id, current_step = nil)
@roster_id = roster_id
@current_step = current_step || STEPS[0]
end
def run
case @current_step
when "PhoneInsertWorker"
worker = Object.const_get(@current_step)
roster = Roster.find(@roster_id)
worker.perform_async(roster.phone.id, self.to_json)
when "RosterLinkToSchoolWorker"
worker = Object.const_get(@current_step)
worker.perform_async(@roster_id, self.to_json)
when "RosterLinkToSchoolAddressWorker"
worker = Object.const_get(@current_step)
worker.perform_async(@roster_id, self.to_json)
else
Rails.logger.info "Finished AddIndividiualCmd for roster [#{@roster_id}]"
end
end
def next
current_step_index = STEPS.index(@current_step)
@current_step = current_step_index.nil? ? nil : STEPS[(current_step_index + 1)]
run
end
def to_json(*a)
{
"json_class" => self.class.name,
"data" => {'roster_id' => @roster_id, 'current_step' => @current_step}
}.to_json(*a)
end
def self.json_create(o)
new(o['data']['roster_id'], o['data']['current_step'])
end
end
class RosterLinkToSchoolWorker
include Sidekiq::Worker
include MyHelper
def perform(roster_id, cmd_json = nil)
roster = Roster.find(roster_id)
link_roster_to_school(roster, cmd_json)
end
def link_roster_to_school(roster, cmd_json)
my_helper_method(roster)
if cmd_json.present?
cmd = JSON.load(cmd_json)
cmd.next()
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment