Module: SafetyNet

Defined in:
lib/safety_net.rb

Instance Method Summary collapse

Instance Method Details

#dump_table(table_name) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/safety_net.rb', line 2

def dump_table(table_name)
  table_name = table_name.to_s
  db_host, db_name, db_user, db_pass = get_db_config

  mysqldump = get_command_path('mysqldump')
  if mysqldump == 'SKIP!'
    puts "WARNING: Skipping dump of #{table_name}"
  else
    date = Time.now.to_s(:number)
    backup_file = File.join(RAILS_ROOT, 'tmp', "#{table_name}_#{date}.sql")

    host = `hostname`.chomp
    puts "** Backing up #{table_name} to #{backup_file} on #{host} **"
    system "#{mysqldump} -h#{db_host} -u#{db_user} -p#{db_pass} #{db_name}" \
           " #{table_name} > #{backup_file}"
    if $?.exitstatus != 0
      raise "UNABLE TO BACKUP #{table_name}.  Bugging out."
    end

    puts '** Backup success **'
  end
end

#get_command_path(command) ⇒ Object



59
60
61
62
63
64
65
66
67
# File 'lib/safety_net.rb', line 59

def get_command_path(command)
  path = `which #{command}`.chomp
  if path.blank?
    print "What is the full path to #{command} (or type 'SKIP!')? "
    gets.chomp
  else
    path
  end
end

#get_db_configObject



53
54
55
56
57
# File 'lib/safety_net.rb', line 53

def get_db_config
  db_config = ActiveRecord::Base.connection.instance_values["config"]
  return [db_config[:host], db_config[:database], db_config[:user],
          db_config[:password]]
end

#restore_table(table_name) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/safety_net.rb', line 25

def restore_table(table_name)
  table_name = table_name.to_s
  db_host, db_name, db_user, db_pass = get_db_config

  mysql= get_command_path('mysql')
  if mysql== 'SKIP!'
    puts "WARNING: Skipping restore of #{table_name}"
  else
    tmp_dir = File.join(RAILS_ROOT, 'tmp')
    file_name = Dir.entries(tmp_dir).select do |name|
      name.match(/^#{table_name}_\d+\.sql$/)
    end.sort.last

    if !file_name
      raise "UNABLE TO RESTORE #{table_name}.  Bugging out."
    end

    restore_file = File.join(tmp_dir, file_name)
    puts "** Restoring #{table_name} from #{restore_file} **"
    system "#{mysql} -h#{db_host} -u#{db_user} -p#{db_pass} #{db_name}" \
           " < #{restore_file}"
    if $?.exitstatus != 0
      raise "UNABLE TO RESTORE #{table_name}.  Bugging out."
    end
    puts '** Restore success **'
  end
end