Class: CopyDb::DumpDb

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

Instance Method Summary collapse

Instance Method Details

#dumpObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/copydb.rb', line 12

def dump
  
  anonymizer = CopyDb::Config.read_anonymize_config
  
  output = File.new(File.expand_path('db/copydb_dumped_data.yml'), "w+")
  yml = [self.schema_version]
  self.tables.each do |table|
    if anonymizer.has_key?(table)
      yml << self.table_dump_anonymous(table,anonymizer[table])
    else
      yml << self.table_dump(table)
    end
  end
  output.write(yml.to_yaml)
  output.close
end

#schema_versionObject



77
78
79
# File 'lib/copydb.rb', line 77

def schema_version
   ActiveRecord::Migrator.current_version
end

#table_column_names(table) ⇒ Object



33
34
35
# File 'lib/copydb.rb', line 33

def table_column_names(table)
  ActiveRecord::Base.connection.columns(table).map { |c| c.name }
end

#table_dump(table) ⇒ Object



37
38
39
40
41
42
43
44
45
# File 'lib/copydb.rb', line 37

def table_dump(table)
  rs = ActiveRecord::Base.connection.execute("SELECT * FROM #{table}")
  yml = Array.new
  yml << table
  rs.each do |r|
    yml << r
  end
  yml
end

#table_dump_anonymous(table, anonymize_column_configurations) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/copydb.rb', line 47

def table_dump_anonymous(table,anonymize_column_configurations)
  
  column_names = Array.new
  anonymizing_types = Array.new
  
  anonymize_column_configurations.each do |anonymize_column_configuration|
    column_names << anonymize_column_configuration.keys[0]
    anonymizing_types << anonymize_column_configuration.values[0]
  end
  
  rs = ActiveRecord::Base.connection.execute("SELECT * FROM #{table}")
  yml = Array.new
  yml << table
  rs.each do |result|
    resultHash = Hash.new
    result.each do |result_column,result_value|          
      
      if column_names.include?(result_column)
        anonymize_type = anonymizing_types[(column_names.index(result_column))]
        resultHash[result_column] = CopyDb::Anonymizer.anonymize(anonymize_type)
      else
        resultHash[result_column] = result_value
      end
                
    end
    yml << resultHash
  end
  yml
end

#tablesObject



29
30
31
# File 'lib/copydb.rb', line 29

def tables
  ActiveRecord::Base.connection.tables.reject { |table| ['schema_info', 'schema_migrations'].include?(table) }
end