Refactoring a simple script to clean a mysql database in ruby -


i created following script wipe mysql database (and reset primary keys of each table). i'm wondering how should refactor it, , how pull in pluralize activesupport.

code:

model_dir = file.expand_path("app/models")  dir.chdir(model_dir) files = dir.glob(file.join("**", "*.rb"))  files.map! |file|   file[0..-4] + "s" end  print "this wipe database. continue? (y/n): " if $stdin.gets.chomp.downcase == "y"   files.each |f|     puts "wiping #{f}.."     activerecord::base.connection.execute "truncate table #{f};"   end else   puts "terminating script..." end 

my logic this, every file in models directory without .rb , pluralized represented table in database, that's how got list of tables relevant application.

i run command: rails runner script/cleandb.rb

how should refactored, , how can pull in pluralize?

based on rails conventions, should able achieve in safer way (for example if have specific table name prexises or table names models) following code:

    print "this wipe database. continue? (y/n): "     if $stdin.gets.chomp.downcase == "y"       # iterate on model definition files       dir["#{rails.root}/app/models/**/*.rb"].map |model_filename|          # file base_name         model_file_basename = file.basename(model_filename,file.extname(model_filename))         # model class file basename         model_class = model_file_basename.camelize.constantize         # ask model (activerecord::base subclass) give table_name         table_name = model_class.table_name          # wipe table         puts "wiping table #{table_name}.."         activerecord::base.connection.execute "truncate table #{table_name};"       end     else       puts "terminating script..."     end 

see documentation on table_names: http://apidock.com/rails/activerecord/modelschema/classmethods/table_name


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -