[英]Sinatra Set Settings (Ruby)
在Ruby中使用Sinatra,您可以執行以下操作來設置服務器的設置:
set :myvariable, "MyValue"
然后使用settings.myvariable
在模板等任何位置訪問它。
在我的腳本中,我需要能夠將這些變量重新設置為默認值。 我認為最簡單的方法是在Sinatra服務器啟動時以及需要進行更改時,執行一個執行所有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
函數,這是我做錯了嗎?
您試圖在MyApp
的類范圍內調用set_settings()
,但是用於定義它的helper
方法僅將其定義為在get... do...end
塊內使用。
如果希望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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.