In Sinatra(Ruby), how should I create global variables which are assigned values only once in the application lifetime?

后端 未结 4 1513
生来不讨喜
生来不讨喜 2020-12-08 10:32

In Sinatra, I\'m unable to create global variables which are assigned values only once in the application lifetime. Am I missing something? My simplified code looks like thi

4条回答
  •  粉色の甜心
    2020-12-08 10:55

    class WebApp < Sinatra::Base
      configure do
        set :my_config_property, 'hello world'
      end
    
      get '/' do
        "#{settings.my_config_property}"
      end
    end
    

    Beware that if you use Shotgun, or some other Rack runner tool that reloads the code on each request the value will be recreated each time and it will look as if it's not assigned only once. Run in production mode to disable reloading and you will see that it's only assigned on the first request (you can do this with for example rackup --env production config.ru).

提交回复
热议问题