namespace :db do # tests: # test empty opt.models # test populated opt.models # test no_id option # test limit option # test empty table but valid seed # test no-data # Write by default to db/seeds.rb # make filename optional with FILE env variable # should ignore append if file doesn't exist # # rake db:seed:dump WITH_ID=true MODELS=User,Product LIMIT=1 NO_DATA=true APPEND=true INDENT=8 FILE=/tmp/seeds.rb # namespace :seed do desc =< :environment do # config opts = {} opts['with_id'] = !ENV["WITH_ID"].nil? opts['no-data'] = !ENV['NO_DATA'].nil? opts['models'] = ENV['MODELS'] || (ENV['MODEL'] ? ENV['MODEL'] : "") opts['file'] = ENV['FILE'] || "#{Rails.root}/db/seeds.rb" opts['append'] = (!ENV['APPEND'].nil? && File.exists?(opts['file']) ) ar_options = ENV['LIMIT'].to_i > 0 ? { :limit => ENV['LIMIT'].to_i } : {} indent = " " * (ENV['INDENT'].nil? ? 2 : ENV['INDENT'].to_i) models = opts['models'].split(',').collect {|x| x.underscore.singularize } new_line = "\r\n" seed_rb = "" Dir['app/models/*.rb'].each do |f| model_name = File.basename(f, '.*') if models.include?(model_name) || models.empty? create_hash = "" model = model_name.camelize.constantize arr = [] arr = model.find(:all, ar_options) unless opts['no-data'] arr = arr.empty? ? [model.new] : arr arr.each_with_index { |r,i| attr_s = []; r.attributes.each { |k,v| attr_s.push("#{k.to_sym.inspect} => #{v.inspect}") unless k == 'id' && !opts['with_id'] } create_hash << (i > 0 ? ",#{new_line}" : new_line) << indent << '{ ' << attr_s.join(', ') << ' }' } seed_rb << "#{new_line}#{model_name.pluralize} = #{model_name.camelize}.create(#{create_hash}#{new_line})#{new_line}" end end File.open(opts['file'], (opts['append'] ? "a" : "w")) { |f| unless opts['append'] cont =<