Class: SlashMigrate::DropIndexMigration

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

Overview

Builds a migration that drops an existing index. remove_index is reversible when given the column(s) — Rails re-creates the index on rollback — so we always emit the ‘column:` form (plus unique:/name: when they aren’t the convention) and keep the migration a plain def change.

Instance Method Summary collapse

Constructor Details

#initialize(table:, index:) ⇒ DropIndexMigration

Returns a new instance of DropIndexMigration.



7
8
9
10
# File 'app/services/slash_migrate/drop_index_migration.rb', line 7

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

Instance Method Details

#columnsObject



12
13
14
# File 'app/services/slash_migrate/drop_index_migration.rb', line 12

def columns
  Array(@index.columns).map(&:to_s)
end

#migration_basenameObject



20
21
22
# File 'app/services/slash_migrate/drop_index_migration.rb', line 20

def migration_basename
  "remove_index_on_#{columns.join("_and_")}_from_#{@table}"
end

#migration_class_nameObject



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

def migration_class_name
  "RemoveIndexOn#{columns.map(&:camelize).join("And")}From#{@table.camelize}"
end

#migration_sourceObject



31
32
33
34
35
36
37
38
39
# File 'app/services/slash_migrate/drop_index_migration.rb', line 31

def migration_source
  [
    "class #{migration_class_name} < ActiveRecord::Migration[#{ActiveRecord::Migration.current_version}]",
    "  def change",
    "    #{remove_statement}",
    "  end",
    "end"
  ].join("\n") + "\n"
end

#remove_statementObject



24
25
26
27
28
29
# File 'app/services/slash_migrate/drop_index_migration.rb', line 24

def remove_statement
  statement = "remove_index :#{@table}, column: #{column_argument}"
  statement += ", unique: true" if @index.unique
  statement += ", name: #{@index.name.inspect}" unless conventional_name?
  statement
end

#write!Object



41
42
43
# File 'app/services/slash_migrate/drop_index_migration.rb', line 41

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