Last active
October 1, 2020 21:21
-
-
Save dougalcorn/b1ff80aad5e7b0d84e05d72d340859fa to your computer and use it in GitHub Desktop.
Order processing from the database based on status
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
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 | |
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
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