Skip to content

Instantly share code, notes, and snippets.

@padi
Forked from existentialmutt/db_fixtures_export.rake
Last active April 8, 2020 10:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save padi/b0363901eca95c80bc8c80a9d4d89e95 to your computer and use it in GitHub Desktop.
Save padi/b0363901eca95c80bc8c80a9d4d89e95 to your computer and use it in GitHub Desktop.
Generate fixtures from db. Readable by rake db:fixtures:load
# https://gist.github.com/kuboon/55d4d8e862362d30456e7aa7cd6c9cf5
namespace 'db:fixtures' do
desc "generate fixtures from the current database"
task :export => :environment do
Rails.application.eager_load!
models = defined?(ApplicationRecord) ? ApplicationRecord.descendants : ActiveRecord::Base.descendants
models.each do |model|
puts "exporting: #{model}"
# e.g. Namespace::Class -> test/fixtures/namespace/class.yml
model_name = model.name
model_name = model_name.pluralize if model.pluralize_table_names?
model_name = model_name.underscore
filepath = Rails.root.join('test/fixtures', "#{model_name}.yml")
FileUtils.mkdir_p filepath.dirname
filepath.open('w') do |file|
hash = {}
model.find_each do |r|
key = r.try(:name) || "#{filepath.basename('.*')}_#{r.id}"
hash[key] = r.attributes.except(:password_digest)
end
file.write "# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html\n\n"
file.write hash.to_yaml
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment