Created
April 25, 2012 19:52
-
-
Save Irio/2492849 to your computer and use it in GitHub Desktop.
db:dump_data and db:load_data
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
#largely based on http://devblog.michaelgalero.com/2008/11/03/custom-rake-tasks-in-merb-data-import/ | |
require 'rake' | |
ENV['ENVIRONMENT'] = 'test' if ENV['ENVIRONMENT'].nil? | |
# DB tasks | |
namespace :db do | |
require 'dm-core' | |
require 'dm-types' | |
require 'dm-timestamps' | |
require 'dm-constraints' | |
require 'dm-validations' | |
require 'dm-migrations' | |
require 'dm-serializer' | |
desc "Dump data from the current environment's DB." | |
task :dump_data do | |
#NOTE: Decimals in your models do not dump!!! I changed mine to Float for this purpose | |
dir = "/Users/irio/Code/MyTraining/dev/db" #Change to suit | |
FileUtils.mkdir_p(dir) | |
FileUtils.chdir(dir) | |
boot_repository | |
DataMapper::Model.descendants.entries.each do |table| | |
puts "Dumping #{table}..." | |
File.open("#{table}.yml", 'w+') { |f| f.print table.all.to_yaml } | |
end | |
end | |
desc "Load data (from spec/db/*.yml) into the current environment's DB." | |
task :load_data do | |
dir = "/Users/irio/Code/MyTraining/spec/db" | |
FileUtils.chdir(dir) | |
boot_repository | |
DataMapper::Model.descendants.entries.each do |table| | |
yaml_file = "#{dir}/#{table}.yml" | |
if File.exists?(yaml_file) | |
puts "Loading #{table} data..." | |
YAML.load_file(yaml_file).each do |fixture| | |
table.create( fixture ) | |
end | |
end | |
end | |
end | |
def boot_repository | |
DataMapper.setup(:default, 'postgres://elland:[email protected]/my_training_dev') | |
Dir["/Users/irio/Code/MyTraining/app/models/*.rb"].each { |model| require model } | |
DataMapper.finalize if DataMapper.respond_to?(:finalize) | |
DataMapper.auto_migrate! # Destructively recreates all tables and indexes | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment