Skip to content

Instantly share code, notes, and snippets.

@blowmage
Created December 6, 2022 11:45
Show Gist options
  • Save blowmage/50d355792aca411eeba7aa58da742165 to your computer and use it in GitHub Desktop.
Save blowmage/50d355792aca411eeba7aa58da742165 to your computer and use it in GitHub Desktop.
Rails Rake task to dump the current environment's database into fixture files.
namespace :db do
namespace :fixtures do
desc "Dumps the current environment's database into fixtures (uses FIXTURES_PATH)"
task dump: :environment do
Rails.application.eager_load!
models = ApplicationRecord.descendants.reject { |model| model.primary_key.nil? }
fixture_files = ENV["FIXTURES"].to_s.split(",")
if fixture_files.any?
models = models.select { |model| fixture_files.include? model.name.pluralize.underscore }
end
models.each do |model|
fixture_scope = model.all.order(model.primary_key)
next if fixture_scope.none?
fixture_dir = ENV["FIXTURES_PATH"] || "test/fixtures"
fixture_file = Rails.root.join fixture_dir, "#{model.name.pluralize.underscore}.yml"
fixture_data = fixture_scope.map do |record|
[
"#{model.name.demodulize.underscore}_#{record[model.primary_key]}",
record.attributes.as_json.slice(*model.column_names)
]
end
fixture_yaml = Hash[fixture_data].to_yaml.gsub(/\A---\n/, "")
FileUtils.mkdir_p File.dirname fixture_file
File.write fixture_file, fixture_yaml
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment