0

I created the following script to wipe a mysql database (and reset the primary keys of each table). I'm wondering how I should refactor it, and how I could pull in pluralize from ActiveSupport.

Code:

MODEL_DIR = File.expand_path("app/models")

Dir.chdir(MODEL_DIR)
files = Dir.glob(File.join("**", "*.rb"))

files.map! do |file|
  file[0..-4] + "s"
end

print "This will WIPE your database. Continue? (y/n): "
if $stdin.gets.chomp.downcase == "y"
  files.each do |f|
    puts "Wiping #{f}.."
    ActiveRecord::Base.connection.execute "TRUNCATE TABLE #{f};"
  end
else
  puts "Terminating script..."
end

My logic was this, every file in the models directory without the .rb and pluralized represented a table in the database, so that's how I got a list of the tables relevant to this application.

I run it with this command: rails runner script/cleandb.rb

How should this be refactored, and how can I pull in pluralize?

Senjai
  • 1,811
  • 3
  • 20
  • 40
  • How you should change your code is opinion based and not the type of question for Stack Overflow. Please read the help section: http://stackoverflow.com/help/dont-ask Try to use pluralize and if it doesn't work, post the specifics on the problem you are having. – xaxxon Aug 24 '13 at 03:55
  • Hi, why not just use show tables in mysql to list all tables and truncate them? – Bigxiang Aug 24 '13 at 06:20
  • Try to post this on: http://codereview.stackexchange.com/ – Martin Aug 24 '13 at 06:48

1 Answers1

3

Based on Rails conventions, you should be able to achieve this in a safer way (for example if you have specific table name prexises or table names for your models) with the following code:

    print "This will WIPE your database. Continue? (y/n): "
    if $stdin.gets.chomp.downcase == "y"
      # iterate over all model definition files
      Dir["#{Rails.root}/app/models/**/*.rb"].map do |model_filename| 
        # get the file base_name
        model_file_basename = File.basename(model_filename,File.extname(model_filename))
        # get the model class from the file basename
        model_class = model_file_basename.camelize.constantize
        # ask the model (ActiveRecord::Base subclass) to give you its table_name
        table_name = model_class.table_name 
        # wipe the 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

NicoArbogast
  • 423
  • 2
  • 4