Class: Multitenant::MigrationBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/generators/multitenant/migrations/migration_builder.rb

Constant Summary collapse

MIGRATION_NAME =
'add_tenant_column_to_models'

Class Method Summary collapse

Class Method Details

.migration_code(actions) ⇒ Object



29
30
31
32
33
34
35
# File 'lib/generators/multitenant/migrations/migration_builder.rb', line 29

def migration_code(actions)
%Q(class AddTenantColumnToModels < ActiveRecord::Migration
  def change
    #{actions.join("\n    ")}
  end
end)
end

.migration_exists?Boolean

Returns:

  • (Boolean)


37
38
39
40
# File 'lib/generators/multitenant/migrations/migration_builder.rb', line 37

def migration_exists?
  migrations = Dir.entries("db/migrate")
  migrations.any? { |m| m.include?(MIGRATION_NAME) }
end

.migration_numberObject



25
26
27
# File 'lib/generators/multitenant/migrations/migration_builder.rb', line 25

def migration_number
  Time.now.utc.strftime("%Y%m%d%H%M%S").to_i
end

.runObject



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/generators/multitenant/migrations/migration_builder.rb', line 8

def run
  return if migration_exists?

  actions = Multitenant::Mysql.configs.models.map { |model_name|
    model = model_name.constantize
    "add_column :#{model.original_table_name}, :tenant, :string"
  }

  dest_path = "db/migrate/#{migration_number}_#{MIGRATION_NAME}.rb"
  migration = File.new(dest_path, "w")
  migration.puts(migration_code(actions))
  migration.close

  p "==================== Generated Migration =================="
  p dest_path
end