Created
June 28, 2012 13:16
-
-
Save netbe/3011314 to your computer and use it in GitHub Desktop.
Extract db tables to fixtures file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace :db do | |
desc 'Create YAML test fixtures from data in an existing database. | |
Defaults to development database. Set RAILS_ENV to override.' | |
task :extract_fixtures => :environment do | |
sql = "SELECT * FROM %s" | |
skip_tables = ["schema_migrations", "sessions"] | |
ActiveRecord::Base.establish_connection | |
tables = ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/) : ActiveRecord::Base.connection.tables - skip_tables | |
tables.each do |table_name| | |
puts "Extracting #{table_name}..." | |
t = Time.now.to_f | |
i = "000" | |
File.open("#{Rails.root.to_s}/spec/fixtures/#{table_name}.yml", 'w') do |file| | |
data = ActiveRecord::Base.connection.select_all(sql % table_name) | |
file.write data.inject({}) { |hash, record| | |
hash["#{table_name}_#{i.succ!}"] = record | |
hash | |
}.to_yaml | |
end | |
puts "#{table_name} done in #{(Time.now.to_f - t).round(2)} sec !" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment