Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # rake db:seed:dump WITH_ID=1 FILE=db/site-seed.rb MODELS=Model, Model
- namespace :db do
- namespace :seed do
- desc "Dump records from the database into db/seeds.rb"
- task :dump => :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.camelize }
- puts models
- new_line = "\n"
- puts "Appending seeds to #{opts['file']}." if opts['append']
- seed_rb = ""
- Module.constants.select do |constant_name|
- constant = eval constant_name
- if not constant.nil? and constant.is_a? Class and constant.superclass == ActiveRecord::Base
- if (models.include?(constant.to_s) || models.empty? )
- model = constant
- model_name = model.to_s
- puts "Adding #{model_name.camelize} seeds."
- 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|
- v = v.class == Time ? "\"#{v}\"" : v.inspect
- attr_s.push("#{k.to_sym.inspect} => #{v}") 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
- end
- File.open(opts['file'], (opts['append'] ? "a" : "w")) { |f|
- puts "Writing #{opts['file']}."
- unless opts['append']
- cont =<<HERE
- # Autogenerated by the db:seed:dump task
- # Do not hesitate to tweak this to your needs
- HERE
- f << cont
- end
- cont =<<HERE
- #{seed_rb}
- HERE
- f << cont
- puts "Done."
- }
- end
- end
- end
Add Comment
Please, Sign In to add comment