Skip to content

Instantly share code, notes, and snippets.

@itsmikeq
Forked from ecleel/db_fixtures_dump.rake
Last active July 8, 2020 15:26
Show Gist options
  • Save itsmikeq/bf42e6d5fdbaacb42b8aa45f7e863072 to your computer and use it in GitHub Desktop.
Save itsmikeq/bf42e6d5fdbaacb42b8aa45f7e863072 to your computer and use it in GitHub Desktop.
Rails 5: Dump Rails db to fixtures
# frozen_string_literal: true
# Original from http://snippets.dzone.com/posts/show/4468 by MichaelBoutros
#
# Optimized version which uses to_yaml for content creation and checks
# that models are ActiveRecord::Base models before trying to fetch
# them from database.
namespace :db do
namespace :fixtures do
desc "Dumps all models into fixtures."
task :dump => :environment do
models = Dir.glob(Rails.root + "app/models/**.rb").map do |s|
Pathname.new(s).basename.to_s.gsub(/\.rb$/, "").camelize
end
# excludes models
excludes = %w(ApplicationRecord)
puts "Found models: " + models.join(", ")
models.reject { |m| m.in?(excludes) }.each do |m|
model = m.constantize
next unless model.ancestors.include?(ActiveRecord::Base)
puts "Dumping model: " + m
entries = model.order(id: :asc).all
increment = 1
fixtures_dir = "#{Rails.root}/#{Rails.env}/fixtures"
FileUtils.mkdir_p(fixtures_dir)
model_file = "#{fixtures_dir}/#{m.underscore.pluralize}.yml"
File.open(model_file, "w") do |f|
entries.each do |a|
attrs = a.attributes
attrs.delete_if { |_, v| v.blank? }
output = { m + "_" + increment.to_s => attrs }
f << output.to_yaml.gsub(/^--- \n/, "") + "\n"
increment += 1
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment