2010-04-07 64 views
6

我在Sinatra::Base中有一个Sinatra应用程序,我想在服务器启动后运行一些代码,我该如何去做这件事?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 

任何想法?

+0

您可能需要更具体以获得一些帮助。 – Beanish 2010-04-07 12:36:25

+0

你是对的 - 我认为这是不言自明的!让我们看看这些修改如何帮助 – 2010-04-11 00:47:27

+1

这不是你问的,但你应该要求'sinatra/base',而不是'sinatra'。从http://www.sinatrarb.com/intro.html#Sinatra::Base%20-%20Middleware,%20Libraries,%20and%20Modular%20Apps:“您的文件应该需要sinatra/base而不是sinatra;否则,所有Sinatra的DSL方法被导入到主命名空间中。“ – mwp 2015-09-30 20:28:22

回答

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 
+2

如果您希望自己的代码运行_after_启动,则可能需要先在方法中调用“super”。 – matt 2013-09-17 20:19:28

+1

此外,这比使用'configure'阻止你的代码在服务器启动后运行,但仅适用于在服务器中构建 - 在使用例如服务器时不起作用。 'rackup'或'瘦开始'。 – matt 2013-09-17 20:20:41

+0

@matt实际上如果你在超级之后调用Launchy,它永远不会被触及,我试过了。 settings.host工作不正常,我将它替换为localhost,因为我只在本地使用它。 – 2013-09-17 21:07:50

2

这是我要做的事尝试;主要运行的是西纳特拉或在一个单独的线程的其他代码:

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 
0

计算器中唯一有效的回答了这个问题(这是问的3-4倍)由levinalexStart 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,但使用薄时,回调仍然是有时被称为一点点服务器接受连接之前。

1

如果你使用的机架(你可能是)我只是发现有您可以在config.ru调用(它在技术上的Rack::Builder的实例方法),让你的服务器运行后的代码块的功能已经开始。它被称为warmup,以下是记录的使用示例:

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

use SomeMiddleware 
run MyApp 
+0

这对于原始问题中的Launchy.open()调用非常有效。尽管首先检查ENV ['RACK_ENV'] ==“development”可能是一个好主意,因为您可能不希望在生产环境中运行。 – dwkns 2017-11-06 13:26:37