Skip to content

Instantly share code, notes, and snippets.

@a2ikm
Last active September 4, 2015 10:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save a2ikm/305404 to your computer and use it in GitHub Desktop.
Save a2ikm/305404 to your computer and use it in GitHub Desktop.
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