Skip to content

Instantly share code, notes, and snippets.

@joxxoxo
Last active December 14, 2015 00:59
Show Gist options
  • Save joxxoxo/5003076 to your computer and use it in GitHub Desktop.
Save joxxoxo/5003076 to your computer and use it in GitHub Desktop.
Rake > MySQL > backup
namespace :db do
desc 'Create db backup'
task :backup => :environment do
db_config = Rails.configuration.database_configuration[Rails.env]
username = db_config['username']
password = db_config['password']
database = db_config['database']
bak_folder = "#{Dir.home}/backups"
FileUtils.mkdir_p(bak_folder)
bak_filename = "#{database}_#{Time.now.to_s(:number)}.sql"
bak_file = "#{bak_folder}/#{bak_filename}"
# create backup
%x{mysqldump -u#{username} -p#{password} --default-character-set=utf8 #{database} -r "#{bak_file}" }
# compress with tar
%x{cd #{bak_folder} && tar czf #{bak_file}.tar.gz -C #{bak_folder} #{bak_filename} && rm #{bak_file}}
# keep 5 last backups
FileUtils.rm_f(Dir["#{bak_folder}/*"][0...-5])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment