2020-07-21 19:25:21 +02:00
|
|
|
# frozen_string_literal: false
|
|
|
|
|
|
|
|
namespace :db do
|
|
|
|
desc 'Convert development DB to Rails test fixtures'
|
2020-07-22 09:45:20 +02:00
|
|
|
task :to_fixtures, [:table] => :environment do |_task, args|
|
2020-07-21 19:25:21 +02:00
|
|
|
TABLES_TO_SKIP = %w[ar_internal_metadata delayed_jobs schema_info schema_migrations].freeze
|
|
|
|
|
|
|
|
begin
|
|
|
|
ActiveRecord::Base.establish_connection
|
|
|
|
ActiveRecord::Base.connection.tables.each do |table_name|
|
|
|
|
next if TABLES_TO_SKIP.include?(table_name)
|
2020-07-22 09:45:20 +02:00
|
|
|
next if args.table && args.table != table_name
|
2020-07-21 19:25:21 +02:00
|
|
|
|
|
|
|
conter = '000'
|
2020-07-22 09:45:20 +02:00
|
|
|
file_path = "#{Rails.root}/test/fixtures/test/#{table_name}.yml"
|
2020-07-21 19:25:21 +02:00
|
|
|
File.open(file_path, 'w') do |file|
|
|
|
|
rows = ActiveRecord::Base.connection.select_all("SELECT * FROM #{table_name}")
|
|
|
|
data = rows.each_with_object({}) do |record, hash|
|
|
|
|
suffix = record['id'].blank? ? conter.succ! : record['id']
|
|
|
|
hash["#{table_name.singularize}_#{suffix}"] = record
|
|
|
|
end
|
|
|
|
puts "Writing table '#{table_name}' to '#{file_path}'"
|
|
|
|
file.write(data.to_yaml)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
ensure
|
|
|
|
ActiveRecord::Base.connection&.close
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|