Skip to content

Instantly share code, notes, and snippets.

@netbe
Created June 28, 2012 13:16
Show Gist options
  • Save netbe/3011314 to your computer and use it in GitHub Desktop.
Save netbe/3011314 to your computer and use it in GitHub Desktop.
Extract db tables to fixtures file
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