Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Sinatra settings from a model

Tags:

ruby

sinatra

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
like image 522
Soup Avatar asked Jul 31 '12 08:07

Soup


2 Answers

i think that you should be able to access it via

Sinatra::Application.settings.documents_path
like image 61
phoet Avatar answered Sep 23 '22 00:09

phoet


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.

like image 36
Soup Avatar answered Sep 23 '22 00:09

Soup