Last active
December 16, 2015 22:20
-
-
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.
This file contains hidden or 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
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