Class: SetAsPrimary::Generators::SetAsPrimaryGenerator

Inherits:
Rails::Generators::Base
  • Object
show all
Includes:
Rails::Generators::Migration
Defined in:
lib/generators/set_as_primary/set_as_primary_generator.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.next_migration_number(dirname) ⇒ Object



57
58
59
# File 'lib/generators/set_as_primary/set_as_primary_generator.rb', line 57

def self.next_migration_number(dirname)
  ActiveRecord::Generators::Base.next_migration_number(dirname)
end

Instance Method Details

#copy_migrationObject



17
18
19
20
21
22
# File 'lib/generators/set_as_primary/set_as_primary_generator.rb', line 17

def copy_migration
  migration_template "migration.rb", "db/migrate/add_primary_column_to_#{table_name}.rb",
    migration_version: migration_version,
    index_on: index_on,
    support_partial_index: support_partial_index
end

#index_onObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/generators/set_as_primary/set_as_primary_generator.rb', line 28

def index_on
  if owner_key.present?
    klass = table_name.classify.constantize
    owner_association = klass.reflect_on_association(owner_key.to_sym)

    if owner_association.nil?
      raise ActiveRecord::AssociationNotFoundError.new(klass, owner_key)
    end

    owner_id_key = "#{owner_key}_id"

    if owner_association.options[:polymorphic]
      owner_type_key = "#{owner_key}_type"
      "%i[#{owner_id_key} #{owner_type_key} #{flag_name}]"
    else
      "%i[#{owner_id_key} #{flag_name}]"
    end
  else
    ":#{flag_name}"
  end
end

#migration_versionObject



24
25
26
# File 'lib/generators/set_as_primary/set_as_primary_generator.rb', line 24

def migration_version
  "[#{ActiveRecord::VERSION::MAJOR}.#{ActiveRecord::VERSION::MINOR}]"
end

#support_partial_indexObject



50
51
52
53
54
55
# File 'lib/generators/set_as_primary/set_as_primary_generator.rb', line 50

def support_partial_index
  # NOTE: Partial indexes are only supported for PostgreSQL and SQLite 3.8.0+.
  # Also found that, even if we use SQLite 3.8.0+, we still get a syntax error.
  # So currently we have ignored SQLite.
  ActiveRecord::Base.connection.adapter_name.downcase.to_sym == :postgresql
end