Skip to content

Instantly share code, notes, and snippets.

@jakl
Last active December 16, 2015 22:20
Show Gist options
  • Save jakl/5506347 to your computer and use it in GitHub Desktop.
Save jakl/5506347 to your computer and use it in GitHub Desktop.
Is it possible to automatically dump test/development data from a production rails app? Here's a rake task (./lib/tasks/dump.rake) that starts trying to do so.
require 'rubygems'
require 'csv'
require 'pry'
desc "Dump a representative set of test/dev data"
task :dump => :environment do
#Load models so they are available for the ActiveRecord::Base.descendants call
Dir.foreach("#{Rails.root}/app/models") do |f|
require f if f =~ /.*\.rb/
end
#Build a hash of table names to model names
models = ActiveRecord::Base.descendants.reduce({}) do |hash, d|
hash[d.table_name] = d.name
hash
end
#Grab all tables according to the DB (might not match our models exactly)
tables = ActiveRecord::Base.connection.tables
#Remember which tables don't have models
no_model_tables = tables.select do |t|
! models.include? t
end
#Dump table names, model names, and record counts to a CSV for perusal
CSV.open('table_counts.csv', 'wb') do |csv|
tables.each do |t|
csv << [t, models[t], ActiveRecord::Base.connection.execute("select count(*) from #{t}").first.first]
end
end
#load CSV for binding.pry
table_model_count = CSV.read('table_counts.csv')
#Open a ruby shell to play with data
binding.pry
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment