Guest User

Untitled

a guest
Jul 18th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. # rake db:seed:dump WITH_ID=1 FILE=db/site-seed.rb MODELS=Model, Model
  2. namespace :db do
  3. namespace :seed do
  4. desc "Dump records from the database into db/seeds.rb"
  5. task :dump => :environment do
  6. # config
  7. opts = {}
  8. opts['with_id'] = !ENV["WITH_ID"].nil?
  9. opts['no-data'] = !ENV['NO_DATA'].nil?
  10. opts['models'] = ENV['MODELS'] || (ENV['MODEL'] ? ENV['MODEL'] : "")
  11. opts['file'] = ENV['FILE'] || "#{Rails.root}/db/seeds.rb"
  12. opts['append'] = (!ENV['APPEND'].nil? && File.exists?(opts['file']) )
  13. ar_options = ENV['LIMIT'].to_i > 0 ? { :limit => ENV['LIMIT'].to_i } : {}
  14. indent = " " * (ENV['INDENT'].nil? ? 2 : ENV['INDENT'].to_i)
  15.  
  16. models = opts['models'].split(',').collect {|x| x.underscore.singularize.camelize }
  17. puts models
  18. new_line = "\n"
  19.  
  20. puts "Appending seeds to #{opts['file']}." if opts['append']
  21.  
  22. seed_rb = ""
  23. Module.constants.select do |constant_name|
  24. constant = eval constant_name
  25. if not constant.nil? and constant.is_a? Class and constant.superclass == ActiveRecord::Base
  26. if (models.include?(constant.to_s) || models.empty? )
  27. model = constant
  28. model_name = model.to_s
  29.  
  30. puts "Adding #{model_name.camelize} seeds."
  31.  
  32. create_hash = ""
  33.  
  34. #model = model_name.camelize.constantize
  35. arr = []
  36. arr = model.find(:all, ar_options) unless opts['no-data']
  37. arr = arr.empty? ? [model.new] : arr
  38. arr.each_with_index { |r,i|
  39.  
  40. attr_s = [];
  41.  
  42. r.attributes.each { |k,v|
  43. v = v.class == Time ? "\"#{v}\"" : v.inspect
  44. attr_s.push("#{k.to_sym.inspect} => #{v}") unless k == 'id' && !opts['with_id']
  45. }
  46.  
  47. create_hash << (i > 0 ? ",#{new_line}" : new_line) << indent << '{ ' << attr_s.join(', ') << ' }'
  48. }
  49.  
  50. seed_rb << "#{new_line}#{model_name.pluralize} = #{model_name.camelize}.create([#{create_hash}#{new_line}])#{new_line}"
  51. end
  52. end
  53. end
  54.  
  55. File.open(opts['file'], (opts['append'] ? "a" : "w")) { |f|
  56.  
  57. puts "Writing #{opts['file']}."
  58.  
  59. unless opts['append']
  60. cont =<<HERE
  61. # Autogenerated by the db:seed:dump task
  62. # Do not hesitate to tweak this to your needs
  63. HERE
  64. f << cont
  65. end
  66.  
  67. cont =<<HERE
  68. #{seed_rb}
  69. HERE
  70. f << cont
  71. puts "Done."
  72.  
  73. }
  74. end
  75. end
  76. end
Add Comment
Please, Sign In to add comment