2010-04-06 63 views
2

在Ruby中使用西納特拉您可以通過設置服務器的設置:西納特拉組設定(紅寶石)

set :myvariable, "MyValue" 

,然後用settings.myvariable任何地方訪問它的模板等。

在我的腳本中,我需要能夠重新設置這些變量回落到一堆默認值。我想這樣做,這將是最簡單的方法有執行所有set■在西納特拉服務器開始調用它,當我需要做出改變的函數:

class MyApp < Sinatra::Application 
    helpers do 
    def set_settings 
     s = settings_from_yaml() 
     set :myvariable, s['MyVariable'] || "default" 
    end 
    end 

    # Here I would expect to be able to do: 
    set_settings() 
    # But the function isn't found! 

    get '/my_path' do 
    if things_go_right 
     set_settings 
    end 
    end 
    # Etc 
end 

如上代碼解釋上面,set_settings功能沒有找到,我是這樣錯誤的方式嗎?

回答

5

你試圖調用set_settings()MyApp範圍內,但您用來定義它只定義它爲get... do...end塊內部使用helper方法。

如果你想set_settings()可用靜態地(在類加載時間,而不是在請求處理時間),你需要將它定義爲一個類的方法:

class MyApp < Sinatra::Application 

    def self.set_settings 
    s = settings_from_yaml() 
    set :myvariable, s['MyVariable'] || "default" 
    end 

    set_settings 

    get '/my_path' do 
    # can't use set_settings here now b/c it's a class 
    # method, not a helper method. You can, however, 
    # do MyApp.set_settings, but the settings will already 
    # be set for this request. 
    end