Sinatra服务器运行后执行代码

时间:2010-04-07 00:56:23

标签: ruby 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

有什么想法吗?

4 个答案:

答案 0 :(得分:4)

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

尝试扩展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

答案 1 :(得分:2)

我就是这样做的;基本上在一个单独的线程中运行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

答案 2 :(得分:2)

如果你正在使用Rack(你可能是),我发现你可以在config.ru中调用一个函数(技术上是Rack::Builder的实例方法),它允许你运行一个块服务器启动后的代码它被称为warmup,这里是记录的用法示例:

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

use SomeMiddleware
run MyApp

答案 3 :(得分:-1)

问题的stackoverflow中唯一有效的答案(被问到3-4次)由levinalex Start and call Ruby HTTP server in the same script提供,我引用:

  

run! in current Sinatra versions获取应用启动时调用的块。

     

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

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时,在服务器接受连接之前,有时会调用回调。