簡體   English   中英

Sinatra設置設置(Ruby)

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM