2010-04-07 56 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