Sinatra集设置(Ruby)

时间:2010-04-06 13:29:31

标签: ruby sinatra

在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函数,我是否采用了错误的方法?

1 个答案:

答案 0 :(得分:5)

您尝试在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