Shef
Shef

Reputation: 1084

How to migrate a database with Sinatra and DataMapper?

I'm trying to write a simple Sinatra web app that contains a task list that can be added to or read from. Right now I'm starting with the list empty.

Here is my code:

require 'sinatra'
require 'slim'
require 'data_mapper'


module TaskerApp
  class App < Sinatra::Base
    configure do
      DataMapper.setup(:default, ENV['DATABASE_URL'] || "sqlite3://#{Dir.pwd}/development.db")
      DataMapper.finalize
      DataMapper.auto_migrate!
      DataMapper.auto_upgrade!
    end

    get '/' do
      @tasks = Task.all
      slim :index
    end
  end

  class Task
    include DataMapper::Resource
    property :id,       Serial
    property :owner,        String, :required => true
    property :time,     DateTime
  end
end

if I ran it like this using rackup config.ru then went to the '\' I would get an error, that the database doesn't exist. To properly create the database I have to run the code Task.auto_migrate! once in the program. My problem is that if I place it in configure do it will run before class Task is called, and will fail, but the only place after that I can put it is in the get '/' do method, where it will run every time the '/' page is loaded, which I think is too much.

What is the proper way of doing this?

Thanks

Upvotes: 1

Views: 411

Answers (1)

Shef
Shef

Reputation: 1084

I solved it by putting the entire Task class in a model.rb file, and adding require './model.rb' at the top of the main file. model.rb looks like this:

require 'rubygems'
require 'data_mapper'
require 'dm-sqlite-adapter'
require 'bcrypt'

DataMapper.setup(:default, ENV['DATABASE_URL'] || "sqlite3://#{Dir.pwd}/development.db")

class Task
  include DataMapper::Resource
  property :id,     Serial
  property :owner,      String, :required => true
  property :time,       DateTime
end

DataMapper.finalize
DataMapper.auto_migrate!
DataMapper.auto_upgrade!
Task.auto_migrate!

Hopefully this helps someone in the future.

Upvotes: 1

Related Questions