Revisions

gist: 51168 Download_button fork
public
Public Clone URL: git://gist.github.com/51168.git
Embed All Files: show embed
rails_fixture_extractor.rake #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
=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