Execute code once Sinatra server is running

后端 未结 4 925
陌清茗
陌清茗 2021-01-18 14:33

I have a Sinatra Application enclosed in Sinatra::Base and I\'d like to run some code once the server has started, how should I go about doing this?

Her

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-18 15:09

    The only valid answer in stackoverflow to this question (which is asked 3-4 times) is given by levinalex on Start and call Ruby HTTP server in the same script, and I quote:

    run! in current Sinatra versions takes a block that is called when the app is started.

    Using that callback you can do this:

    require 'thread'
    
    def sinatra_run_wait(app, opts)
      queue = Queue.new
      thread = Thread.new do
        Thread.abort_on_exception = true
        app.run!(opts) do |server|
          queue.push("started")
        end
      end
      queue.pop # blocks until the run! callback runs
    end
    
    sinatra_run_wait(TestApp, :port => 3000, :server => 'webrick')
    

    This seems to be reliable for WEBrick, but when using Thin the callback is still sometimes called a little bit before the server accepts connections.

提交回复
热议问题