Skip to content

Instantly share code, notes, and snippets.

@ashmoran
Created October 31, 2009 18:57
Show Gist options
  • Save ashmoran/223187 to your computer and use it in GitHub Desktop.
Save ashmoran/223187 to your computer and use it in GitHub Desktop.
class DatabaseResetter
def initialize(options)
@environment = options[:environment]
@files_to_watch = options[:files_to_watch] || "schema/migrations/**/*.rb"
end
def reset_if_required
if migrations_changed_since_last_database_reset?
reset
else
puts "*** Skipping database reset (migrations not changed since last run)"
puts "*** Run `#{reset_command}` if necessary, or touch a migration"
end
end
private
def database_reset_time_file
"log/database_reset_time_#{@environment}"
end
def reset
puts "*** Resetting #{@environment} database"
run_reset_command_or_raise
log_database_reset_time
puts "*** #{@environment.capitalize} database reset"
end
def migrations_changed_since_last_database_reset?
most_recent_migration_file_change_timestamp > last_database_reset_timestamp
end
def most_recent_migration_file_change_timestamp
Dir[@files_to_watch].map { |filename|
File.mtime(filename)
}.max
end
def last_database_reset_timestamp
File.open(database_reset_time_file) do |file|
Time.parse(file.readline)
end
rescue Errno::ENOENT
Time.at(0)
end
def log_database_reset_time
File.open(database_reset_time_file, "w") do |file|
file.puts(Time.new)
end
end
def run_reset_command_or_raise
raise "Command failed: #{reset_command}" unless run_reset_command
end
def run_reset_command
system(reset_command)
end
def reset_command
"rake db:reset MERB_ENV=#{@environment}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment