Sinatra服务器运行后执行代码

我在Sinatra::Base附带了一个Sinatra应用程序,我想在服务器启动后运行一些代码,我该怎么做呢?

这是一个例子:

 require 'sinatra' require 'launchy' class MyServer < Sinatra::Base get '/' do "My server" end # This is the bit I'm not sure how to do after_server_running do # Launches a browser with this webapp in it upon server start Launchy.open("http://#{settings.host}:#{settings.port}/") end end 

有任何想法吗?

使用配置块不是正确的方法。 无论何时加载文件,都会运行命令。

尝试延长run!

 require 'sinatra' require 'launchy' class MyServer < Sinatra::Base def self.run! Launchy.open("http://#{settings.host}:#{settings.port}/") super end get '/' do "My server" end end 

我就是这样做的; 基本上在单独的线程中运行sinatra或其他代码:

 require 'sinatra/base' Thread.new { sleep(1) until MyApp.settings.running? p "this code executes after Sinatra server is started" } class MyApp < Sinatra::Application # ... app code here ... # start the server if ruby file executed directly run! if app_file == $0 end 

如果你正在使用Rack(你可能是),我发现你可以在config.ru调用一个函数(它在技术上是Rack::Builder一个实例方法),它可以让你在服务器运行后运行一段代码。已经开始了。 它被称为warmup ,这是记录的用法示例:

 warmup do |app| client = Rack::MockRequest.new(app) client.get('/') end use SomeMiddleware run MyApp 

这个问题的stackoverflow中唯一有效的答案(被问到3-4次)是由levinalex在Start上给出的, 并在同一个脚本中调用Ruby HTTP服务器 ,我引用:

run! 在当前的Sinatra版本中,需要一个在启动应用程序时调用的块。

使用该回调您可以这样做:

 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') 

这对于WEBrick来说似乎是可靠的,但是当使用Thin时,在服务器接受连接之前,有时仍会调用回调。