2010-04-06 51 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 
相关问题