Ad

Run Code In Sinatra After The Response Has Been Sent

- 1 answer

I'm pretty new to Ruby and Sinatra and I'm trying to set up a basic sinatra server to listen for HTTP post requests, and then process the data.

I need to send the response within 5 seconds or the server (shopify) which sends the POST thinks that the request has failed and sends it again. To avoid that, Shopify advises to defer processing until after the response has been sent.

I'm not sure how to trigger my processing once Sinatra has sent the response.

Will this work ?

require 'sinatra'
require 'json'

webhook_data = Order.new
post '/' do
    request.body.rewind
    data = request.body.read
    webhook_data.parsed_json = JSON.parse(data)
    puts "My response gets sent here, right ?"
end

after do
    #DO MY PROCESSING HERE
end

Is there any better way to do this ?

Ad

Answer

You can use any solution for background jobs processing. Here is example for Sidekiq usage with Sinatra.

You can try to use Threads as well:

set :threaded, true

post '/' do
    request.body.rewind
    data = request.body.read
    Thread.new do
      # data processing staff goes here
    end
    # here goes response
end
Ad
source: stackoverflow.com
Ad