Question

I'd like to maintain a data structure on a Sinatra or Rails server (doesn't matter) that is accessible for all HTTP requests that arrive to it (i.e. to support concurrent modification). I don't want to rely on a database or similar because that doesn't allow me to code callbacks for the modification of this data structure and put concurrent blocks on the HTTP response threads.

Since HTTP is stateless there's apparently no easy way to achieve this.

How can I make a process to maintain data in the background for all the requests that arrive to an HTTP server without reliying on external programs and middleware? Does it require me to modify Rails or Sinatra to achieve this? Is there any alternative even outside ruby?

Was it helpful?

Solution

When using Sinatra, you can just code in a thread at the end of your application:

http://blog.markwatson.com/2011/11/ruby-sinatra-web-apps-with-background.html

Using this, you could maintain a worker that would do things even as http requests come in and out.

Sinatra also has the methods before and after which run before and after each request, respectively.

So if you wanted to add data to a data structure before each request is handled you could:

before do puts request end

Using these tools, you can easily achieve what you want to do.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top