访问全局Sinatra对象

时间:2014-01-04 06:54:19

标签: ruby sinatra web-frameworks

我正在尝试在我的Sinatra应用程序中编写一个帮助器类。我试图以某种方式访问​​Sinatra属性但始终获得nil。我的代码如下:

app.rb:

configure do
  enable :sessions
  set :session_secret, "STHSTHSTH"
  # DATABASE_URL is provided by environment, or can be set on the command line
  # For instance: DATABASE_URL=mysql://localhost/freecoins rackup
  # will run the app with the database at localhost/freecoins.
  DataMapper.setup(:default, ENV['DATABASE_URL'])
  # These set it up to automatically create/change tables when
  # their models are updated.
  DataMapper.auto_migrate!
  DataMapper.auto_upgrade!

  # Here we read in the config file and parse the JSON from it.
  config = JSON.parse(File.read("config/config.json"))

  # Then we loop through each element in the JSON object and
  # assign it to Sinatra's settings.
  # They are accessed via settings.key anywhere in the app,
  # especially in some of the routes.
  config.each do |k, v|
    set k.to_sym, v
  end
end

set :views,  'views'

Dir["routes/*.rb"].each {|file| require_relative file }
Dir["models/*.rb"].each {|file| require_relative file }
Dir["helpers/*.rb"].each {|file| require_relative file }

# This has to be called once all the models have been defined.
DataMapper.finalize

助手类:

class WalletHelper
    @currency = nil
    @client = nil
    def initialize(currency)
        puts $settings #settings is nil here
    end
end

我如何访问应用的属性,例如设置,就像我在get块中一样?

2 个答案:

答案 0 :(得分:2)

您应该尝试Sinatra::Base.settings

答案 1 :(得分:1)

您可能希望看到Sinatra.registerSinatra.helpers

有关详细信息,请参阅http://www.sinatrarb.com/extensions.html