Skip to content

Instantly share code, notes, and snippets.

@existentialmutt
Forked from kuboon/db_fixtures_export.rake
Last active March 25, 2023 21:10
Show Gist options
  • Save existentialmutt/a36d024b0ca7bbf5d3e81fa8b2cd692d to your computer and use it in GitHub Desktop.
Save existentialmutt/a36d024b0ca7bbf5d3e81fa8b2cd692d to your computer and use it in GitHub Desktop.

Revisions

  1. existentialmutt revised this gist Dec 28, 2017. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion db_fixtures_export.rake
    Original file line number Diff line number Diff line change
    @@ -4,7 +4,7 @@ namespace 'db:fixtures' do

    task :export => :environment do
    Rails.application.eager_load!
    models = defined?(AppicationRecord) ? ApplicationRecord.decendants : ActiveRecord::Base.descendants
    models = defined?(ApplicationRecord) ? ApplicationRecord.descendants : ActiveRecord::Base.descendants
    models.each do |model|
    puts "exporting: #{model}"

  2. @kuboon kuboon created this gist May 12, 2017.
    25 changes: 25 additions & 0 deletions db_fixtures_export.rake
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    # lib/tasks/db_fixtures_export.rake
    namespace 'db:fixtures' do
    desc "generate fixtures from the current database"

    task :export => :environment do
    Rails.application.eager_load!
    models = defined?(AppicationRecord) ? ApplicationRecord.decendants : ActiveRecord::Base.descendants
    models.each do |model|
    puts "exporting: #{model}"

    # Hoge::Fuga -> test/fixtures/hoge/fuga.yml
    filepath = Rails.root.join('test/fixtures', "#{model.name.underscore}.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 hash.to_yaml
    end
    end
    end
    end