Skip to content

Instantly share code, notes, and snippets.

@a2ikm a2ikm/gist:305404
Last active Sep 4, 2015

Embed
What would you like to do?
dump database to yaml for fixtures
#
#= 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
You can’t perform that action at this time.