Created
December 28, 2011 13:17
-
-
Save iiska/1527911 to your computer and use it in GitHub Desktop.
Dump Rails db to fixtures
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
# Original from http://snippets.dzone.com/posts/show/4468 by MichaelBoutros | |
# | |
# Optimized version which uses to_yaml for content creation and checks | |
# that models are ActiveRecord::Base models before trying to fetch | |
# them from database. | |
namespace :db do | |
namespace :fixtures do | |
desc 'Dumps all models into fixtures.' | |
task :dump => :environment do | |
models = Dir.glob(RAILS_ROOT + '/app/models/**.rb').map do |s| | |
Pathname.new(s).basename.to_s.gsub(/\.rb$/,'').camelize | |
end | |
puts "Found models: " + models.join(', ') | |
models.each do |m| | |
model = m.constantize | |
next unless model.ancestors.include?(ActiveRecord::Base) | |
puts "Dumping model: " + m | |
entries = model.find(:all, :order => 'id ASC') | |
increment = 1 | |
model_file = RAILS_ROOT + '/test/fixtures/' + m.underscore.pluralize + '.yml' | |
File.open(model_file, 'w') do |f| | |
entries.each do |a| | |
attrs = a.attributes | |
attrs.delete_if{|k,v| v.blank?} | |
output = {m + '_' + increment.to_s => attrs} | |
f << output.to_yaml.gsub(/^--- \n/,'') + "\n" | |
increment += 1 | |
end | |
end | |
end | |
end | |
end | |
end |
@thams 👍 ❤️ 🎉 🎈
I also wrote for newer Rails. https://gist.github.com/kuboon/55d4d8e862362d30456e7aa7cd6c9cf5
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
FWIW, turned this into a gem, (and fixed some things for newer Rails versions). https://github.com/thams/db_fixtures_dump