Class: Struggle::Backup

Inherits:
Object
  • Object
show all
Defined in:
lib/struggle/backup.rb

Instance Method Summary collapse

Constructor Details

#initializeBackup

初始化配置文件



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/struggle/backup.rb', line 19

def initialize
  _config = YAML.load_file("#{Rails.root}/config/backup.yml")
  @@config = _config.merge(YAML.load_file("#{Rails.root}/config/database.yml")[_config["env"]])
  @@config["backup_path"] = File.expand_path(@@config["backup_path"], Rails.root)
  @@now = Time.now
  # 备份路径创建
  # 参数now,创建时间,默认当前
  @@dir = "#{@@config["backup_path"]}/#{@@now.year}/#{@@now.month}/#{@@now.day}"
  unless Dir.exist? @@dir
    FileUtils.mkdir_p @@dir
  end
end

Instance Method Details

#database_backupObject

备份数据库



33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/struggle/backup.rb', line 33

def database_backup
  _filename = "#{@@config["database"]}-#{@@now.strftime("%Y%m%d%H%M%S")}"
  filename = @@config["adapter"] == "oracle_enhanced" ? "#{_filename}.dmp" : "#{_filename}.sql"
  if @@config["adapter"] == "mysql2"
    system("mysqldump -u#{@@config["username"]} #{@@config["database"]}>#{filename}")
  elsif @@config["adapter"] == "postgresql"
    system("pg_dump -U #{@@config["username"]} -d #{@@config["database"]} -E utf8 -f #{filename} -w")
  elsif @@config["adapter"] == "oracle_enhanced"
    system("exp #{@@config["username"]}/#{@@config["password"]}@#{@@config["database"]} file=#{filename} full=y")
  end
  Struggle::ZipTool.file(filename, "#{@@dir}/#{_filename}.zip")
  File.delete filename
end

#doObject

备份



66
67
68
69
70
71
72
# File 'lib/struggle/backup.rb', line 66

def do
  database_backup
  file_backup
  if @@config["mode"] == "ftp"
    ftp_backup
  end
end

#file_backupObject

备份文件



48
49
50
51
52
53
54
# File 'lib/struggle/backup.rb', line 48

def file_backup
  @@config["asset_paths"].each do |assetPath|
    assetPath = "#{Rails.root}/#{assetPath}"
    ridx = assetPath.rindex("/") || 0
    Struggle::ZipTool.dir(assetPath, "#{@@dir}/#{assetPath[ridx..assetPath.length - 1]}-#{@@now.strftime("%Y%m%d%H%M%S")}.zip")
  end
end

#ftp_backupObject

ftp上传



57
58
59
60
61
62
63
# File 'lib/struggle/backup.rb', line 57

def ftp_backup
  _filename = "backup-#{@@now.strftime("%Y%m%d%H%M%S")}.zip"
  ftp_config = @@config["ftp"]
  Struggle::ZipTool.dir(@@dir, _filename)
  Struggle::FtpTool.new(ftp_config["ip"], ftp_config["username"], ftp_config["password"]).put(_filename, ftp_config["backup_path"])
  File.delete _filename
end