在Ruby中使用Sinatra,您可以通过执行以下操作来设置服务器的设置:
set :myvariable, "MyValue"
Run Code Online (Sandbox Code Playgroud)
然后在模板等的任何地方访问它settings.myvariable.
在我的脚本中,我需要能够将这些变量重新设置为一堆默认值.我认为最简单的方法set是在Sinatra服务器的开头执行所有调用它的函数,当我需要进行更改时:
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
Run Code Online (Sandbox Code Playgroud)
正如上面的代码中所解释的那样,set_settings找不到该函数,我是否采用了错误的方法?
您正尝试set_settings()在类范围内调用MyApp,但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
Run Code Online (Sandbox Code Playgroud)