# Original from http://snippets.dzone.com/posts/show/4468 by MichaelBoutros # Forked from https://gist.github.com/ecleel/3dc89a753bac6a54bf8d170f63256f19 # # Optimized version which uses to_yaml for content creation and checks # that models are ActiveRecord::Base models and not abstract class before trying to fetch # them from database. # # Also supports nested resources and namespaces them correctly # # Tested in Rails 6.0.0 # namespace :db do namespace :fixtures do desc 'Dumps all models into fixtures.' task :dump => :environment do models_path = Pathname.new(Rails.root + 'app/models') models = Dir.glob(Rails.root + 'app/models/**/*.rb').map do |model| dir_and_name = Pathname.new(model).relative_path_from(models_path).to_s dir_and_name.gsub(/\.rb$/,'').camelize end # include only ActiveRecord models and non-abstract class models models.select! do |m| m = m.constantize m.ancestors.include?(ActiveRecord::Base) && !m.abstract_class end puts "Found models: #{models.to_sentence}" puts "=> Dumping models:" models.each do |m| model = m.constantize model_file = "#{Rails.root}/test/fixtures/#{m.underscore.pluralize}.yml" puts " \x1b[94m#{m}\x1b[0m to \x1b[94m#{Pathname.new(model_file).relative_path_from(Rails.root)}\x1b[0m" increment = 1 entries = model.order(id: :asc).all FileUtils.mkdir_p(File.dirname(model_file)) File.open(model_file, 'w') do |f| entries.each do |a| attrs = a.attributes attrs.delete_if { |_k, v| v.blank? } output = { m + '_' + increment.to_s => attrs } f << output.to_yaml.gsub(/^--- \n/,'') + "\n" increment += 1 end end end end end end