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?
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:
See documentation on table_names: http://apidock.com/rails/ActiveRecord/ModelSchema/ClassMethods/table_name