Module: AutoMigrations

Defined in:
lib/data_plan/generators/migration/lib/auto_migrations.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



39
40
41
42
43
44
45
46
# File 'lib/data_plan/generators/migration/lib/auto_migrations.rb', line 39

def self.included(base)
  base.extend ClassMethods
  class << base
    cattr_accessor :tables_in_schema, :indexes_in_schema, :views_in_schema
    self.tables_in_schema, self.indexes_in_schema, self.views_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
# File 'lib/data_plan/generators/migration/lib/auto_migrations.rb', line 3

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

  load(File.join(DB_PROJECT_ROOT, 'db', 'plan.rb'))
  ActiveRecord::Migration.drop_unused_tables
  ActiveRecord::Migration.drop_unused_views
  ActiveRecord::Migration.drop_unused_indexes

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

.schema_to_migrationObject



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

def self.schema_to_migration
  schema = File.read(File.join(DB_PROJECT_ROOT, "db", "plan.rb")) rescue begin
    puts "Please copy your schema.rb file to plan.rb before generating migrations!"
    raise
  end
  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 - ["schema_info"]).map do |table| 
              "    drop_table :#{table}\n"
            end.join
  schema << "  end\nend\n"
  migration_file = File.join(DB_PROJECT_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