Skip to content

Instantly share code, notes, and snippets.

@twada
Created September 14, 2009 08:42
Show Gist options
  • Save twada/186565 to your computer and use it in GitHub Desktop.
Save twada/186565 to your computer and use it in GitHub Desktop.
require 'yaml'
require 'active_record'
class ActiveRecord::Migrator
class << self
TARGET_METHODS = %w[up down]
TARGET_METHODS.each do |name|
define_method("#{name}_with_database_dump") do |*args|
dump_current_database
self.send("#{name}_without_database_dump", *args)
end
alias_method_chain name, :database_dump
end
def dump_current_database
config_path = File.join(RAILS_ROOT, 'config', 'database.yml')
db = YAML::load(ERB.new(IO.read(config_path)).result)[RAILS_ENV]
identifier = Time.now.utc.strftime("%Y%m%d%H%M%S")
case db['adapter']
when 'mysql'
file = "#{RAILS_ROOT}/tmp/#{RAILS_ENV}_dump_#{identifier}.sql.bz2"
puts "## dump database to [#{file}]"
system("mysqldump -u #{db['username']} --password=#{db['password']} --add-drop-table #{db['database']} | bzip2 -c > #{file}")
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment