Skip to content

Instantly share code, notes, and snippets.

@dougalcorn
Last active October 1, 2020 21:21
Show Gist options
  • Save dougalcorn/b1ff80aad5e7b0d84e05d72d340859fa to your computer and use it in GitHub Desktop.
Save dougalcorn/b1ff80aad5e7b0d84e05d72d340859fa to your computer and use it in GitHub Desktop.
Order processing from the database based on status
class Order
def self.ready_to_queue
where(status: new_states)
end
def self.new_states
['created', '', nil]
end
# This will select the next available order to be processed and queue it for
# sidekiq ensuring that it's not already being processed
def self.queue_next_order
Order.transaction do
order = Order.lock.ready_to_queue.first
if new_states.include?(order.status)
order.status = 'queued' && order.save!
SendOrderWorker.perform_async(order.id)
else
queue_next_order
end
end
end
class SendOrderWorker
include Sidekiq::Worker
def perform(order_id)
order = Order.find(order_id)
order.status = 'running' && order.save
# serialze and send the order
order.status = 'success' && order.save
rescue
order.status = 'error' && order.save
ensure
# This queues the next job once this worker is done
Order.queue_next_order
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment