Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top