日期:2014-05-16  浏览次数:20420 次

数据备份和恢复代码,用于数据库迁移

apposs要从sqlite3迁移到mysql,支持所谓生产环境,所以写了段代码用于迁移数据,这种代码写过N遍了,所以决定放到博客上作为备忘,顺便展示一下ruby结合active record模式的方便

?

namespace :data do
  desc "backup all data"
  task :backup => :environment do
    Dir.mkdir "data" unless File.exist? "data"
    (ActiveRecord::Base.connection.tables - ["schema_migrations"]).each{|t|
      clazz = t.camelize.singularize
      File.open("data/#{clazz}.yml",'w') do |f| f.puts clazz.constantize.all.to_yaml end
    }
  end

  desc "restore all data"
  task :restore => :environment do
    require 'yaml'
    Dir['data/*'].each{|f|
      f =~ /\/(.+)\.yml/
      clazz = $1
      Object.send :remove_const, clazz rescue nil
      eval("class #{clazz} < ActiveRecord::Base; end")
      YAML.load(File.new(f)).each{|o|
        new_o = o.class.new(o.attributes)
        new_o.id = o.id
        new_o.save!
      }
    }
  end

end
?