-
-
Save iangreenleaf/897534a599ba652a5d3d 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
# | |
#= dump database to yaml for fixtures | |
# | |
# originated by elm200 <http://d.hatena.ne.jp/elm200/20070928/1190947947> | |
# | |
#== install | |
# | |
# move this file to RAILS_ROOT/lib/tasks/extract_fixtures.rake | |
# | |
namespace :db do | |
fixtures_dir = "#{Rails.root}/tmp/fixtures/" | |
namespace :fixtures do | |
desc <<-DESC | |
"Extract database data to the tmp/fixtures/ directory. | |
Use FIXTURES=table_name[,table_name...] to specify table names to extract. | |
Otherwise, all the table data will be extracted." | |
DESC | |
task :dump => :environment do | |
def fixture_entry(table_name, obj) | |
res = [] | |
begin | |
klass = table_name.singularize.camelize.constantize | |
rescue NameError | |
return | |
end | |
res << "#{table_name.singularize}#{obj['id']}:" | |
klass.columns.each do |column| | |
x = obj[column.name] | |
if column.text? then x = "\"#{x}\"" end | |
if column.type == :datetime then x = x.try(:to_formatted_s, :db) end | |
res << " #{column.name}: #{x}" | |
end | |
res.join("\n") | |
end | |
sql = "SELECT * FROM %s" | |
skip_tables = ["schema_migrations"] | |
ActiveRecord::Base.establish_connection | |
sh "mkdir -p #{fixtures_dir}" | |
if ENV['FIXTURES'] | |
table_names = ENV['FIXTURES'].split(/,/) | |
else | |
table_names = (ActiveRecord::Base.connection.tables - skip_tables) | |
end | |
table_names.each do |table_name| | |
File.open("#{fixtures_dir}#{table_name}.yml", "w") do |file| | |
objects = ActiveRecord::Base.connection.select_all(sql % table_name) | |
objects.each do |obj| | |
entry = fixture_entry(table_name, obj) | |
file.write entry + "\n\n" unless entry.nil? | |
end | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment