I am trying to write a simple quiz game in sinatra and I need to have common objects accessible for all users (lobby state, chat messages etc.). The problem is that Sinatra reloads the code after every request and objects become in initial state. How to implement it?
Well, the topic is a bit tricky. Sinatra actually doesn't reset the server state:
require 'sinatra'
GlobalState = {}
GlobalState[:some_counter] = 0
get '/' do
response = "GlobalState[:some_counter]: #{GlobalState[:some_counter]}"
GlobalState[:some_counter] += 1
response
end
This code has nothing wrong: if you run it and go to http://localhost:4567
you will see GlobalState[:some_counter]
incremented as expected.
But it is discouraged for the following reasons, that are mainly related to the web nature of the application:
For these reasons the web apps data management is not trivial. Anyway don't worry, you don't have to reinvent the wheel; the solutions are in hand:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With