Class: Automigration::Migrator
- Inherits:
-
Object
- Object
- Automigration::Migrator
- Defined in:
- lib/automigration/migrator.rb
Constant Summary collapse
- @@system_tables =
[]
- @@migration_paths =
[]
- @@model_paths =
[]
Class Method Summary collapse
- .load_all_models! ⇒ Object
- .set_migration_paths(paths) ⇒ Object
- .set_model_paths(paths) ⇒ Object
- .set_system_tables(tables) ⇒ Object
Instance Method Summary collapse
-
#initialize(options = {}) ⇒ Migrator
constructor
A new instance of Migrator.
- #update_schema! ⇒ Object
Constructor Details
#initialize(options = {}) ⇒ Migrator
Returns a new instance of Migrator.
31 32 33 34 35 36 37 38 |
# File 'lib/automigration/migrator.rb', line 31 def initialize( = {}) .assert_valid_keys(:skip_output, :models) self.class.load_all_models! @models = [:models] || ActiveRecord::Base.descendants = end |
Class Method Details
.load_all_models! ⇒ Object
22 23 24 25 26 27 28 29 |
# File 'lib/automigration/migrator.rb', line 22 def self.load_all_models! @@model_paths.each do |path| Dir[File.("**/*.rb", path)].each do |file| name = file.sub(path.to_s + '/', '').sub(Regexp.new(File.extname(file) + '$'), '') ActiveSupport::Dependencies.constantize(name.classify) end end end |
.set_migration_paths(paths) ⇒ Object
14 15 16 |
# File 'lib/automigration/migrator.rb', line 14 def self.set_migration_paths(paths) @@migration_paths = paths end |
.set_model_paths(paths) ⇒ Object
18 19 20 |
# File 'lib/automigration/migrator.rb', line 18 def self.set_model_paths(paths) @@model_paths = paths end |
.set_system_tables(tables) ⇒ Object
10 11 12 |
# File 'lib/automigration/migrator.rb', line 10 def self.set_system_tables(tables) @@system_tables = tables end |
Instance Method Details
#update_schema! ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/automigration/migrator.rb', line 40 def update_schema! log "Models: " + @models.map(&:to_s).join(', ') # update tables tables = ['schema_migrations'] @models.each do |model| update_model_schema(model) tables << model.table_name end #remove unused tables (connection.tables - tables - @@system_tables).each do |table| connection.drop_table(table) log "Remove table '#{table}'", :red end # clean migration table if connection.table_exists?('schema_migrations') && !@@migration_paths.empty? sql = "SELECT version FROM schema_migrations;" migrations_in_db = connection.execute(sql).map{|row| row.is_a?(Hash) ? row['version'] : row.first } current_migrations = [] @@migration_paths.each do |path| Dir[File.("*.rb", path)].each do |m_file| File.basename(m_file) =~ /(\d{14})/ current_migrations << $1 end end (migrations_in_db - current_migrations).each do |m| log "Clean migration '#{m}'", :red sql = "DELETE FROM schema_migrations WHERE version = '#{m}';" connection.execute(sql) end end end |