Access Sinatra settings from a model

霸气de小男生 提交于 2019-12-10 17:56:47

问题


I have a modular Sinatra app. I'm setting some custom variables in my configure block and want to access these settings in my model.

The problem is, I get a NoMethodError when I try and access my custom settings from MyModel. Standard settings still seem to work fine though. How can I make this work?

# app.rb
require_relative 'models/document'

class App < Sinatra::Base
  configure do
    set :resource_path, '/xfiles/i_want_to_believe'
  end

  get '/' do
    @model = MyModel.new
    haml :index
  end
end

# models/my_model.rb
class MyModel
  def initialize
    do_it
  end
  def do_it
    ...
    settings.resource_path # no method error
    ...
    settings.root # works fine
  end
end

回答1:


i think that you should be able to access it via

Sinatra::Application.settings.documents_path



回答2:


I ended up doing:

#document.rb
class Document
  def self.documents_path=(path)
    @documents_path = path
  end
  def self.documents_path
    @documents_path
  end
  ...
end

#app.rb
configure do
  set :documents_path, settings.root + "/../documents/" 
  Document.documents_path = settings.documents_path
end

then just using Document.documents_path inside my find method.



来源:https://stackoverflow.com/questions/11735622/access-sinatra-settings-from-a-model

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!