在 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
函数,我的处理方式是否错误?
最佳答案
您正在尝试调用 set_settings()
在 MyApp
的 class 范围内,但是helper
您用来定义它的方法仅将其定义为在 get... do...end
内部使用 block 。
如果你想要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
关于ruby - Sinatra 设置设置 (Ruby),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2585131/