Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

rake db:backup:create

  • Loading branch information...
commit ef46c1353a8731e5c914e8a6fe342a36f25b39a0 1 parent cab0af4
Antono Vasiljev authored
Showing with 69 additions and 0 deletions.
  1. +28 −0 lib/tasks/backup.rake
  2. +41 −0 lib/tasks/database.rake
28 lib/tasks/backup.rake
View
@@ -0,0 +1,28 @@
+namespace :db do
+ namespace :backup do
+
+ def backup_directory
+ ENV['BACKUP_DIR'] ||= File.join(Rails.root, 'backups')
+ end
+
+ # Set the VERSION to the latest if it's not set
+ task :latest do
+ last = Dir["#{backup_directory}/*/"].sort.last
+ puts ENV['VERSION'] ||= File.basename(last) if last
+ end
+
+ # Setup environment variables for the schema and fixtures tasks
+ task :setup => :environment do
+ ENV['VERSION'] ||= Time.now.utc.strftime('%Y%m%d%H%M%S')
+ backup = File.join(backup_directory, ENV['VERSION'])
+ FileUtils.mkdir_p backup
+ ENV['FIXTURES_DIR'] = backup
+ end
+
+ desc 'Create a new backup of the database'
+ task :create => [:setup, 'db:fixtures:dump']
+
+ desc 'Restore a backup of the database. Use VERSION to specify a version other than the latest.'
+ task :restore => [:latest, :setup, 'db:fixtures:load']
+ end
+end
41 lib/tasks/database.rake
View
@@ -0,0 +1,41 @@
+# These tasks replace the built-in Rails tasks for dumping and loading the schema,
+# allowing you to specify the FIXTURES_DIR to use for dumping and loading.
+Rake.application.instance_eval do
+ @tasks.delete "db:fixtures:load"
+ @tasks.delete "db:fixtures:dump"
+end
+
+
+namespace :db do
+ namespace :fixtures do
+ desc "Load fixtures into the current environment's database."
+ task :load => :environment do
+ prepare_connection_details
+ db_to_load = Dir["#{@fixtures_dir}/*"].first.split("/").last
+ cmd = "mongorestore #{@auth_options} --drop -d #{@db_name} #{@fixtures_dir}/#{db_to_load}"
+ command_runner(cmd)
+ end
+
+ desc "Create bson fixtures from data in the current environment's database."
+ task :dump => :environment do
+ prepare_connection_details
+ cmd = "mongodump #{@auth_string} --host #{@host} --port #{@port} -d #{@db_name} -o #{@fixtures_dir}"
+ command_runner(cmd)
+ end
+ end
+end
+
+def command_runner(cmd)
+ puts cmd
+ `#{cmd}`
+end
+
+def prepare_connection_details
+ @host, @port = Mongoid.database.connection.host_to_try
+ @db_name = Mongoid.database.name
+ auths = Mongoid.database.connection.auths
+ if auths.length > 0
+ @auth_string = "-u #{auths[0]["username"]} -p #{auths[0]["password"]}"
+ end
+ @fixtures_dir = ENV['FIXTURES_DIR'] || File.join(Rails.root, 'test', 'fixtures')
+end
Please sign in to comment.
Something went wrong with that request. Please try again.