Sharing Ruby Variables Between Sinatra Queries

I am trying to write a simple quiz game in sinatra, and I need the shared objects to be accessible to all users (lobby status, chat messages, etc.). The problem is that Sinatra reloads the code after each request, and the objects go back to their original state. How to implement this?

+4
source share
2 answers

Well, the topic is a bit more complicated. Sinatra does not actually 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

There is nothing wrong with this code: if you run it and go over http://localhost:4567you will see that it GlobalState[:some_counter]grows as expected.

, - :

  1. Ruby, , . , ,
  2. -, . :
    1. : . , Ruby
    2. : , , ,
  3. , : , HTTP ( ). :
    1. : , HTML5 Local Storage...
    2. : ( , , cookie)

- . , , ; :

+9

- . cookie.

0

Source: https://habr.com/ru/post/1528195/


All Articles