Created
January 23, 2009 20:06
-
-
Save PatrickTulskie/51168 to your computer and use it in GitHub Desktop.
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
=begin | |
Written by: Patrick Tulskie (http://github.com/patricktulskie) | |
WARNING: This will delete any previous fixture dumps that you've made with the script before it runs. | |
Review the code and understand it before running it. | |
=end | |
namespace :db do | |
desc 'Create YAML test fixtures from data in an existing database. Defaults to development database automagically. | |
Set RAILS_ENV to override. Set FIXTURES to specify what fixtures to extract.' | |
task :extract_fixtures => :environment do | |
sql = "SELECT * FROM %s" | |
skip_tables = ["schema_info", "sessions"] # You can add more tables in here that you want to skip. | |
ActiveRecord::Base.establish_connection | |
tables = ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/) : ActiveRecord::Base.connection.tables - skip_tables | |
fixtures_location = "#{RAILS_ROOT}/db/fixture_dump" | |
if File.exists?(fixtures_location) && File.directory?(fixtures_location) | |
# If the fixture_dump directory already exists, let's purge it now to prevent errors and duplication. | |
FileUtils.rm_r(fixtures_location, :force => true) | |
end | |
Dir.mkdir("#{RAILS_ROOT}/db/fixture_dump") | |
tables.each do |table_name| | |
i = "000" | |
File.open("#{RAILS_ROOT}/db/fixture_dump/#{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 | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment