Overwrite rake tasks in sinatra project and activerecord

50 Views Asked by At

I have a Sinatra fun project and I want to improve my rake tasks so that everytime I create a new migration and migrate it I don't have to manually run them with RACK_ENV=test bundle exec rake db:migrate again. Just like in Rails you run rake db:mgirate and the migration is run in both development and test environments. I tried overwriting the rake tasks in my Rakefile, the migrate task works but rollback does not. I've already tried everything. Appreciate your help.

namespace 'db' do
  task 'migrate' do
    Rake::Task['db:migrate'].invoke

    return if ENV.fetch('SINATRA_ENV') == 'production'

    # Run migration in test env as well
    ENV['RACK_ENV'] = 'test'

    ActiveRecord::Base.establish_connection(
      adapter: 'postgresql',
      database: "sinatra_project_#{ENV['RACK_ENV']}"
    )
    ActiveRecord::Tasks::DatabaseTasks.migrate
  end

  task 'rollback' do
    Rake::Task['db:rollback'].clear
    Rake::Task['db:rollback'].invoke

    return if ENV.fetch('SINATRA_ENV') == 'production'

    # Rollback migration in test env as well
    ENV['RACK_ENV'] = 'test'

    ActiveRecord::Base.establish_connection(
      adapter: 'postgresql',
      database: "sinatra_project_#{ENV['RACK_ENV']}"
    )
    Rake::Task['db:rollback'].clear
    Rake::Task['db:rollback'].invoke
  end
end
0

There are 0 best solutions below