Last active
September 4, 2015 10:04
-
-
Save a2ikm/305404 to your computer and use it in GitHub Desktop.
dump database to yaml for 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
# | |
#= 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 = [] | |
klass = table_name.singularize.camelize.constantize | |
res << "#{table_name.singularize}#{obj['id']}:" | |
klass.columns.each do |column| | |
x = obj[column.name] | |
if column.text? then x = "\"#{x}\"" end | |
res << " #{column.name}: #{x}" | |
end | |
res.join("\n") | |
end | |
sql = "SELECT * FROM %s ORDER BY id" | |
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| | |
file.write fixture_entry(table_name, obj) + "\n\n" | |
end | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment