jt4e1q
Last Updated: February 25, 2016
·
2.864K
· thejbsmith
623c7791975da8c200970a5e6b27d40c

Disable destructive rake tasks by environment

Few tasks in Rails can be as destructive as db:drop. Running rake db:drop in development usually isn't a big deal since the data is most likely easily replaced. But what if you accidentally run a rake db:drop on your production application?

Being a good developer, you should have a recent backup that you can use, but this is still a hassle. Hopefully nothing like this will ever happen, but why not cover your ass anyway? With a few lines of code we can override tasks like db:drop in a production environment.

/lib/tasks/db.rake

if Rails.env == 'production'
  tasks = Rake.application.instance_variable_get '@tasks'
  tasks.delete 'db:reset'
  tasks.delete 'db:drop'
  namespace :db do
    desc 'db:reset not available in this environment'
    task :reset do
      puts 'db:reset has been disabled'
    end
    desc 'db:drop not available in this environment'
    task :drop do
      puts 'db:drop has been disabled'
    end
  end
end

Now, if you actually get to the point where you need to use this in your production environment, you will need to comment out this code and redeploy. Sure, it can be kind of a hassle, but in my opinion the hassle of commenting this out is much less of a hassle than restoring an entire database.

Say Thanks
Respond