grautur
grautur

Reputation: 30485

persisting variables in sinatra

Suppose I have a Sinatra app that simply prints out random numbers from 0-9:

get '/' do
  rand(10)
end

I want to make sure that the app does not print out the same number as last time (so it's not really random -- this is just a toy example, in any case):

# I want to do something like this... This code doesn't work.
prev_rand = nil
get '/' do
  curr_rand = rand(10)
  while prev_rand and curr_rand == prev_rand
    curr_rand = rand(10)
  end
  prev_rand = curr_rand
  curr_rand
end

How would I do this? Using the above example doesn't quite work, as the prev_rand inside the get '/' block is a local variable (not the same as the one outside the block), so changing its value doesn't persist.

(I don't quite understand Sinatra scope.)

Upvotes: 2

Views: 1163

Answers (1)

Kunal
Kunal

Reputation: 66

You could store "prev_rand" as a setting, which is an application-level variable that's accessible within the request context via the "settings" object:

configure do
  set :prev_rand, nil
end

get '/' do
  begin
    curr_rand = rand(10)
  end while curr_rand == settings.prev_rand
  set :prev_rand, curr_rand
  curr_rand
end

For more info: http://www.sinatrarb.com/configuration.html

Upvotes: 3

Related Questions