-
Notifications
You must be signed in to change notification settings - Fork 1
/
csv_backup.rake
39 lines (37 loc) · 912 Bytes
/
csv_backup.rake
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
require 'csv'
task :csv_backup => :environment do
Dir[Rails.root.join('app/models/*.rb').to_s].each do |filename|
klass = File.basename(filename, '.rb').camelize.constantize
if klass != ApplicationRecord
backup_table(klass);
end
end
puts "\nCSV backup complete"
end
def backup_table(table)
table_name = table.name.demodulize
count = 0
print table_name
(25 - table_name.length).times do
print '.'
end
CSV.open(Rails.root.join('db', 'csv_backups', table_name + '.csv'), 'w') do |csv|
# Print out the headers
headers = []
table.columns.each do |header|
headers.push(header.name)
end
csv << headers
# Add all the records
records = table.all
records.each do |record|
row = []
record.attributes.each_pair do |name, value|
row.push(value)
end
count += 1
csv << row
end
end
puts count.to_s
end