Instantly share code, notes, and snippets.

What would you like to do?
Sync your development database and file upload folders with whatever your staging/production server currently has
# Task has the following dependencies
# net/ssh gem [gem install net-ssh]
# net/sftp gem [gem install net-sftp]
# rsync command line utility
# yamb_db rails plugin [ruby script/plugin install git://]
desc "This task will make your development environment download and import a fresh copy of your staging database and also sync any folders such as image uploads so you can quickly replicate your staging/production server content locally"
task :sync_with_staging => :environment do
@remote_host = ''
@remote_user = 'yoursshuser'
@remote_password = "yoursshpassword"
@remote_environment = "staging"
@remote_path_to_rails = "/home/rails/myproject/current"
@directories_to_sync = {"/home/rails/myproject/shared/system" => "#{RAILS_ROOT}/public"}
require 'net/ssh'
require 'net/sftp'
#Delete our old local data.yml file
File.delete("#{RAILS_ROOT}/db/data.yml") if File::exists?("#{RAILS_ROOT}/db/data.yml")
#Create a new data.yml file on the staging server
Net::SSH.start(@remote_host, @remote_user, :password => @remote_password) do |ssh|
output = ssh.exec!("hostname")
ssh.exec "rake -f #{@remote_path_to_rails}/Rakefile RAILS_ENV=#{@remote_environment} db:data:dump"
#Now download the data.yml file over the ssh connection
ssh.sftp.connect do |sftp|!("#{@remote_path_to_rails}/db/data.yml", "#{RAILS_ROOT}/db/data.yml")
#Import the new data.yml file
#Sync the uploads
@directories_to_sync.each do |remote_path, local_path|
sh("rsync -vra #{@remote_user}@#{@remote_host}:#{remote_path} #{local_path}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment