-
-
Save petrosp/c3a3e7154761498f608ecb42d0d83c1d to your computer and use it in GitHub Desktop.
Dump fixtures from the current environment's database
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
# Source: http://blog.ivanilves.com/2016/rails-dump-fixtures-from-db/ | |
# Usage: | |
# * rake db:fixtures:dump to dump all models. | |
# * rake db:fixtures:dump MODELS="user billing_account" to dump only User and BillingAccount models. | |
# * rake db:fixtures:dump EXCEPT="user billing_account" to dump all, except for User and BillingAccount models. | |
# | |
namespace :db do | |
namespace :fixtures do | |
def all_models | |
# HT: mustafa http://blog.ivanilves.com/2016/rails-dump-fixtures-from-db/#comment-6562 | |
if Rails::VERSION::STRING.split('.')[0].to_i <= 4 | |
ActiveRecord::Base.subclasses | |
else | |
ApplicationRecord.subclasses | |
end | |
end | |
def selected_models | |
return nil unless ENV['MODELS'] | |
selected_model_names = ENV['MODELS'].split(/\s+|,/).map(&:camelcase) | |
all_models.select { |m| selected_model_names.include?(m.name) } | |
end | |
def excluded_models | |
return nil unless ENV['EXCEPT'] | |
excluded_model_names = ENV['EXCEPT'].split(/\s+|,/).map(&:camelcase) | |
all_models.reject { |m| excluded_model_names.include?(m.name) } | |
end | |
desc "Dump fixtures from the current environment's database" | |
task dump: :environment do | |
Rails.application.eager_load! | |
models = excluded_models || selected_models || all_models | |
models.each do |model| | |
file_name = "#{Rails.root}/test/fixtures/#{model.name.underscore.pluralize}.yml" | |
puts "Dumping: #{model.name} => #{file_name}" | |
File.open(file_name, 'w') do |file| | |
data = {} | |
model.all.map(&:attributes).each do |record| | |
data["#{model.name.underscore}_#{record['id'].to_s}"] = record | |
end | |
file.write data.to_yaml | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment