Class: DynamoRecord::TaskHelpers::MigrationRunner

Inherits:
Object
  • Object
show all
Defined in:
lib/dynamo-record/task_helpers/migration_runner.rb

Class Method Summary collapse

Class Method Details

.run(path = 'db/dynamo_migrate') ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/dynamo-record/task_helpers/migration_runner.rb', line 4

def self.run(path='db/dynamo_migrate')
  constants = []
  filename_regexp = /\A([0-9]+)_([_a-z0-9]*)\.?([_a-z0-9]*)?\.rb\z/

  # Sorts the files located in `db/dynamo_migrate` to ensure order is preserved
  Dir[Rails.root.join("#{path}/*.rb")].sort.each do |f|
    raise "Non-numeric prefix: #{f}" if File.basename(f).scan(filename_regexp).first.nil?
    require f

    # finds the constant that was added on the require statement above
    migration_sym = (DynamoMigrate.constants - constants).first
    migration = DynamoMigrate.const_get(migration_sym)
    constants.push migration_sym

    # starts the migration
    yield "Migrating: #{migration}"

    begin
      status = up(migration)
      yield status if status

      status = update(migration)
      yield status if status
    rescue => e
      yield "Migration failed: #{e}"
    end
  end
end

.up(migration) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/dynamo-record/task_helpers/migration_runner.rb', line 33

def self.up(migration)
  return unless migration.respond_to? :up
  case migration.up
  when :exists
    'Table already exists'
  when :migrated
    'Migration successful'
  else
    raise 'Migration failed'
  end
end

.update(migration) ⇒ Object



45
46
47
48
49
50
# File 'lib/dynamo-record/task_helpers/migration_runner.rb', line 45

def self.update(migration)
  return unless migration.respond_to? :update
  status = migration.update
  return 'Migration successful' if status == :updated
  status
end