Class: SlashMigrate::EditColumnMigration

Inherits:
Object
  • Object
show all
Defined in:
app/services/slash_migrate/edit_column_migration.rb

Overview

Builds the migration for editing an existing column — rename and/or change its type, nullability, or default — by diffing the desired column against the original (live) one and emitting only the operations that changed.

change_column (a type change) isn’t auto-reversible, so any edit that includes one is written as explicit up/down. A pure rename stays a clean, auto-reversible def change.

Instance Method Summary collapse

Constructor Details

#initialize(table:, original:, desired:) ⇒ EditColumnMigration

Returns a new instance of EditColumnMigration.



10
11
12
13
14
# File 'app/services/slash_migrate/edit_column_migration.rb', line 10

def initialize(table:, original:, desired:)
  @table = table.to_s
  @original = original
  @desired = desired
end

Instance Method Details

#changed?Boolean

Returns:

  • (Boolean)


16
17
18
# File 'app/services/slash_migrate/edit_column_migration.rb', line 16

def changed?
  renamed? || type_changed? || null_changed? || default_changed?
end

#migration_basenameObject



37
38
39
# File 'app/services/slash_migrate/edit_column_migration.rb', line 37

def migration_basename
  simple_rename? ? "rename_#{@original.name}_in_#{@table}" : "change_#{column_name}_in_#{@table}"
end

#migration_class_nameObject



29
30
31
32
33
34
35
# File 'app/services/slash_migrate/edit_column_migration.rb', line 29

def migration_class_name
  if simple_rename?
    "Rename#{@original.name.camelize}In#{@table.camelize}"
  else
    "Change#{column_name.camelize}In#{@table.camelize}"
  end
end

#migration_sourceObject



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'app/services/slash_migrate/edit_column_migration.rb', line 41

def migration_source
  body =
    if simple_rename?
      method_block("change", up_statements)
    else
      method_block("up", up_statements) + [""] + method_block("down", down_statements)
    end

  lines = ["class #{migration_class_name} < ActiveRecord::Migration[#{ActiveRecord::Migration.current_version}]"]
  lines += body
  lines << "end"
  lines.join("\n") + "\n"
end

#reversible_as_change?Boolean

Returns:

  • (Boolean)


25
26
27
# File 'app/services/slash_migrate/edit_column_migration.rb', line 25

def reversible_as_change?
  simple_rename?
end

#tightening_null?Boolean

NOT NULL on a column with existing NULL rows fails without a backfill; flag it.

Returns:

  • (Boolean)


21
22
23
# File 'app/services/slash_migrate/edit_column_migration.rb', line 21

def tightening_null?
  null_changed? && !@desired.allow_null?
end

#write!Object



55
56
57
# File 'app/services/slash_migrate/edit_column_migration.rb', line 55

def write!
  [MigrationFileWriter.write(basename: migration_basename, source: migration_source)]
end