Search code examples
sinatra

Using a config block at the top of the file throws error


I'm trying to set a connection to the database (using Sequel) before the model appears. Well it must be that way but am getting an error

undefined method `configure' for main:Object (NoMethodError)

Here is the code, I don't see anything wrong with setting up the constants there so perhaps it is either something related to the configure block or the config.ru.

require 'sinatra/base'
require 'sequel'
require 'slim'
require 'sass'
require 'sinatra/flash'
require './sinatra/auth'

configure :development do
  password = ENV["PGPASSWORD"]
  DB = Sequel.postgres('development', user: 'postgres', password: password, host: 'localhost')
end

configure :production do
  DB = Sequel.connect(ENV['DATABASE_URL'])
end

Here is the rack file. I tried to do the connect statement in there but failed (so far)

require 'sinatra/base'
require './main'
require './song'
require 'sequel'

map('/songs') { run SongController }
map('/') { run Website}

Not understanding why the configure block will not work.

Edit: I'm guessing because the call to the SongController is in config.ru, the connect statements need to be in there as well. Edit: And further along , since this is a modular app, a config.yml is probably my best option.


Solution

  • You're using sinatra/base. That means you'll have to use a subclass:

    require 'sinatra/base'
    require 'sequel'
    require 'slim'
    require 'sass'
    require 'sinatra/flash'
    require './sinatra/auth'
    
    class MyApp < Sinatra::Base
      configure :development do
        password = ENV["PGPASSWORD"]
        DB = Sequel.postgres('development', user: 'postgres', password: password, host: 'localhost')
      end
    
      configure :production do
        DB = Sequel.connect(ENV['DATABASE_URL'])
      end
    
      run! if app_file == $0 
    end
    

    NB: You can just use require sinatra and all the magic without using subclasses will be abailable. Or, if you need a modular app, use Sinatra::Application and you will have all the magic included. See sinatra's readme for full coverage on the differences.