开发者

Sinatra Set Settings (Ruby)

Using Sinatra in Ruby you can set the server's settings by doing:

set :myvariable, "MyValue"

and then access it anywhere in templates etc with settings.myvariable.

In my script I need to be able to re-set these variables falling back to a bunch of defaults. I figured the easiest way to do this would be to have a function that performs all the sets calling it at the start of the Sinatra server and when I need to make开发者_运维问答 the alterations:

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

As explained in the code above, the set_settings function isn't found, am I going about this the wrong way?


You're trying to call set_settings() inside the class scope of MyApp, but the helper method you used to define it only defines it for use inside that get... do...end block.

If you want set_settings() to be available statically (at class-load time instead of at request-process time), you need to define it as a class method:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜