Module: ReversableDataMigration

Defined in:
lib/reversable_data_migration.rb

Instance Method Summary collapse

Instance Method Details

#backup(data, file = nil) ⇒ Object



23
24
25
26
27
28
29
30
31
32
# File 'lib/reversable_data_migration.rb', line 23

def backup data, file=nil
  unless File.directory?(location_backup_files)
    FileUtils.mkdir_p(location_backup_files)
  end
  file = default_or_specific_file(file)
  puts "-- writing backup data (#{data.count} records) to #{file}"
  File.open( file , 'w' ) do |out|
    YAML.dump( data, out ) 
  end
end

#default_backupfileObject



7
8
9
# File 'lib/reversable_data_migration.rb', line 7

def default_backupfile
  "#{location_backup_files}/#{name.underscore}.yml" # name.underscore => name of migration 
end

#default_or_specific_file(file) ⇒ Object



15
16
17
18
19
20
21
# File 'lib/reversable_data_migration.rb', line 15

def default_or_specific_file file
  if file
    full_path_of file
  else
    default_backupfile
  end
end

#destroy_created_records(klass, file = nil) ⇒ Object



34
35
36
37
38
39
# File 'lib/reversable_data_migration.rb', line 34

def destroy_created_records klass, file=nil
  file = default_or_specific_file(file)
  test_record = first_record(file)
  process_records(klass, file){ |object, object_hash| object.destroy }
  raise "Destroying objects failed" if test_record.blank? || test_record[:id].blank? || klass.find_by_id(test_record[:id]) 
end

#full_path_of(file) ⇒ Object



11
12
13
# File 'lib/reversable_data_migration.rb', line 11

def full_path_of file
  "#{location_backup_files}/#{file}.yml"
end

#location_backup_filesObject



3
4
5
# File 'lib/reversable_data_migration.rb', line 3

def location_backup_files
  "#{(Rails.version =~ /^2/) ? RAILS_ROOT : Rails.root.to_s}/db/migrate/backup_data"
end

#restore(klass, file = nil) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/reversable_data_migration.rb', line 41

def restore klass, file=nil
  file = default_or_specific_file(file)
  test_record = first_record file
  puts "-- restore data from #{file}"
  process_records(klass,file) do |object, object_hash|
    object_hash.select{|k,v| k != :id}.each do |key, value|
      object.send("#{key}=", value)
    end
    object.save
  end
end

#restore_batchObject



53
54
55
56
57
58
59
60
# File 'lib/reversable_data_migration.rb', line 53

def restore_batch
  @transaction = true
  @to_delete_after_transaction = []
  yield
  @to_delete_after_transaction.each do |file|
    delete_file(file) 
  end
end