Created
August 11, 2010 11:47
-
-
Save szymon-jez/518858 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
desc ' Creates YAML test fixtures from data in an existing database. | |
Parameters: | |
RAILS_ENV - use to select databese. Default is to development database (eg. RAILS_ENV=test). | |
TABLES - use to select tables to extract. By default all tables are extractd. (eg. TABLES=users,orders). | |
DIR - use to change default (/test/fixtures) write directory (eg. DIR=./db/data).' | |
task :extract => :environment do | |
dir = ENV['DIR'] || "#{RAILS_ROOT}/test/fixtures" | |
sql = "SELECT * FROM %s ORDER BY id ASC" | |
ActiveRecord::Base.establish_connection | |
if ENV['TABLES'] | |
interesting_tables = ENV['TABLES'].split(',') | |
else | |
skip_tables = ['schema_info', 'schema_migrations', 'sessions', 'logged_exceptions', | |
'plugin_schema_info', 'order_types_orders'] | |
interesting_tables = (ActiveRecord::Base.connection.tables - skip_tables) | |
end | |
interesting_tables.each do |table_name| | |
i = "000" | |
File.open("#{dir}/#{table_name}.yml", 'w' ) do |file| | |
data = ActiveRecord::Base.connection.select_all(sql % table_name) | |
puts "Writing #{table_name}.yml..." | |
file.write data.inject({}) { |hash, record| | |
hash["#{table_name}_#{i.succ!}"] = record | |
hash | |
}.to_yaml | |
end | |
end | |
end | |
desc ' Loads data from selected fixtures to a database. | |
Parameters: | |
RAILS_ENV - use to select databese. Default is to development database (eg. RAILS_ENV=test). | |
FIXTURES - use to select fixtures to load in (e.g. FIXTURES=users,orders). | |
DIR - use to change default (/test/fixtures) write directory (eg. DIR=./db/data).' | |
task :load_in => [:environment] do | |
interesting_tables = ENV['FIXTURES'].split(',') | |
dir = ENV['DIR'] || "#{RAILS_ROOT}/test/fixtures" | |
FileUtils.mkdir_p(dir) | |
FileUtils.chdir(dir) | |
interesting_tables.each do |table_name| | |
ActiveRecord::Base.transaction do | |
puts "Clearing #{table_name}..." | |
ActiveRecord::Base.connection.execute "DELETE FROM #{table_name}", "Table Clearance" | |
puts "Loading #{table_name}..." | |
YAML.load_file("#{table_name}.yml").each do |fixture| | |
fixture = fixture[1] | |
ActiveRecord::Base.connection.execute "INSERT INTO #{table_name} (#{fixture.keys.join(",")}) VALUES (#{fixture.values.collect { |value| ActiveRecord::Base.connection.quote(value) }.join(",")})", 'Fixture Insert' | |
end | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment