Created
January 12, 2013 17:49
-
-
Save lucasdavila/4519566 to your computer and use it in GitHub Desktop.
Dumps database records into test fixtures.
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 | |
namespace :fixtures do | |
# by default it task load records from development env, | |
# to change send the RAILS_ENV var, eg: $ rake db:fixtures:dumps RAILS_ENV=production | |
desc 'dumps the database data into test fixtures.' | |
task :dumps => :environment do | |
sql = "SELECT * FROM %s" | |
skip_tables = ['schema_info', 'schema_migrations'] | |
# load all records | |
ActiveRecord::Base.establish_connection | |
tables = (ActiveRecord::Base.connection.tables - skip_tables) | |
puts "\n\n* Loading records from #{Rails.env} environment" | |
puts "* Skipped tables #{skip_tables}\n" | |
tables.each do |table_name| | |
record_name = "#{table_name.singularize}_0" | |
records = ActiveRecord::Base.connection.select_all(sql % table_name) | |
unless records.count > 0 | |
puts "* No #{table_name} found" | |
next | |
end | |
records = records.inject({}) { |hash, record| | |
hash[record_name.next!] = record | |
hash | |
} | |
# write the fixture | |
path = "#{Rails.root}/test/fixtures/#{table_name}.yml" | |
if File.exists? path | |
puts "* Fixture #{path} already exists, please remove or rename it." | |
else | |
puts "* Writing #{records.count} #{table_name}" | |
File.open path, 'w' do |file| | |
file.write records.to_yaml | |
end | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment