One of my clients has a huge application with no test suite. I am helping the company migrate to Rails 2.3 as well as remove some bottlenecks from their code. I needed to convert around 10 look-up tables to YAML’s so that I could load the data as fixtures and test the application properly as I make changes. I scraped together pieces of code from the web and came up with this:
namespace :db do namespace :fixtures do desc 'Create YAML test fixtures from data in an existing database. Defaults to development database. Set RAILS_ENV to override.' task :dump => :environment do sql = "SELECT * FROM %s" skip_tables = ["schema_info"] ActiveRecord::Base.establish_connection(RAILS_ENV) tables=ENV['TABLES'].split(',') tables ||= (ActiveRecord::Base.connection.tables - skip_tables) tables.each do |table_name| i = "000" File.open("#{RAILS_ROOT}/test/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 end end end end
To use, put this code in a file somewhere like RAILS_ROOT/lib/tasks/util/table_to_yml.rake and execute something like:
rake db:fixtures:dump TABLES=lookup_table_1,lookup_table_2,...,lookup_table_nNo TweetBacks yet. (Be the first to Tweet this post)
If you enjoyed this post, make sure you subscribe to my RSS feed!










2 Comments
Extremely useful thanks. Had a project converting legacy data that was normalized, this helped greatly.
change that *not* normalized