Module: AutoMigrations

Defined in:
lib/auto_migrations.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



37
38
39
40
41
42
43
44
# File 'lib/auto_migrations.rb', line 37

def self.included(base)
  base.extend ClassMethods
  class << base
    cattr_accessor :tables_in_schema, :indexes_in_schema
    self.tables_in_schema, self.indexes_in_schema = [], []
    alias_method_chain :method_missing, :auto_migration
  end
end

.runObject



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/auto_migrations.rb', line 3

def self.run
  # Turn off schema_info code for auto-migration
  class << ActiveRecord::Schema
    alias :old_define :define
    attr_accessor :version
    def define(info={}, &block) @version=info[:version]; instance_eval(&block) end
  end

  load(File.join(RAILS_ROOT, 'db', 'schema.rb'))
  ActiveRecord::Migration.drop_unused_tables
  ActiveRecord::Migration.drop_unused_indexes
  ActiveRecord::Migration.update_schema_version(ActiveRecord::Schema.version) if ActiveRecord::Schema.version

  class << ActiveRecord::Schema
    alias :define :old_define
  end
end

.schema_to_migrationObject



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/auto_migrations.rb', line 21

def self.schema_to_migration
  schema = File.read(File.join(RAILS_ROOT, "db", "schema.rb"))
  schema.gsub!(/#(.)+\n/, '')
  schema.sub!(/ActiveRecord::Schema.define(.+)do[ ]?\n/, '')
  schema.gsub!(/^/, '  ')
  schema = "class InitialSchema < ActiveRecord::Migration\n  def self.up\n" + schema
  schema << "\n  def self.down\n"
  schema << (ActiveRecord::Base.connection.tables - %w(schema_info schema_migrations)).map do |table| 
              "    drop_table :#{table}\n"
            end.join
  schema << "  end\nend\n"
  migration_file = File.join(RAILS_ROOT, "db", "migrate", "001_initial_schema.rb")
  File.open(migration_file, "w") { |f| f << schema }
  puts "Migration created at db/migrate/001_initial_schema.rb"
end