Guest User

Untitled

a guest
Jul 19th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. namespace :db do desc "Backup project database. Options: DIR=backups RAILS_ENV=production MAX=7"
  2. task :backup => [:environment] do
  3. datestamp = Time.now.strftime("%Y-%m-%d_%H-%M-%S")
  4. base_path = Rails.root
  5. base_path = File.join(base_path, ENV["DIR"] || "backups")
  6. backup_base = File.join(base_path, 'db_backups')
  7. backup_folder = File.join(backup_base, datestamp)
  8. backup_file = File.join(backup_folder, "#{RAILS_ENV}_dump.sql")
  9. FileUtils.mkdir_p(backup_folder)
  10. db_config = ActiveRecord::Base.configurations[RAILS_ENV]
  11. `mysqldump -u #{db_config['username']} -p#{db_config['password']} -i -c -q #{db_config['database']} > #{backup_file}`
  12. raise "Unable to make DB backup!" if ( $?.to_i > 0 )
  13. `gzip -9 #{backup_file}`
  14. dir = Dir.new(backup_base)
  15. all_backups = dir.entries.sort[2..-1].reverse
  16. puts "Created backup: #{backup_file}"
  17. max_backups = (ENV["MAX"].to_i if ENV["MAX"].to_i > 0) || 7
  18. unwanted_backups = all_backups[max_backups..-1] || []
  19. for unwanted_backup in unwanted_backups
  20. FileUtils.rm_rf(File.join(backup_base, unwanted_backup))
  21. end
  22. puts "Deleted #{unwanted_backups.length} backups, #{all_backups.length - unwanted_backups.length} backups available"
  23. end
  24. end
  25.  
  26. # USAGE
  27. # =====
  28. # rake db:backup
  29. # RAILS_ENV=production rake db:backup
  30. # MAX=14 RAILS_ENV=production rake db:backup
  31. # DIR=another_dir MAX=14 RAILS_ENV=production rake db:backup
Add Comment
Please, Sign In to add comment