Micah Micah - 3 months ago 63
Ruby Question

Sinatra not understanding settings in config.ru?

I'm trying to write a config.ru file for Sinatra where I have one set of database credentials for each environment: development and production. I'm doing the following:


require 'sinatra'
require 'data_mapper'
require 'dm-mysql-adapter'

DataMapper.setup(:default, "mysql://#{settings.db_user}:#{settings.db_password}@#{settings.db_host}/#{settings.db_name}")

# ... the rest of the app


require 'sinatra'
require './app.rb' # the app itself

configure :development do
set :db_name, 'thedatabase'
set :db_user, 'root'
set :db_password, ''
set :db_server, 'localhost'

run Sinatra::Application

But when I attempt to start the app using
ruby app.rb
, I get "undefined method 'db_user' for Sinatra::Application:Class (NoMethodError)".

Generally, I'm just trying to offload all these settings into their own file. If config.ru isn't the place for them, what would be an appropriate way to do this?


Looks like it might be an ordering problem. If that DataMapper.setup(...) line is really at the top level of app.rb, it will be called as soon as you require './app.rb', before configure has run.

It's best not to do any work upon loading a file. Use some form of explicit or lazy initialization instead.