Class: WebammToRails::Sources::Migrations::FilesList

Inherits:
Object
  • Object
show all
Defined in:
lib/webamm_to_rails/sources/migrations/files_list.rb

Instance Method Summary collapse

Constructor Details

#initialize(waml_definition:, database_tables:) ⇒ FilesList

Returns a new instance of FilesList.



9
10
11
12
# File 'lib/webamm_to_rails/sources/migrations/files_list.rb', line 9

def initialize(waml_definition:, database_tables:)
  @waml_definition = waml_definition
  @database_tables = database_tables
end

Instance Method Details

#collectionObject



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/webamm_to_rails/sources/migrations/files_list.rb', line 14

def collection
  migrations = []
  migration_timestamp = Time.now.utc - 1_000
  migration_count = 0

  uuid_presenter = ::WebammToRails::Sources::Migrations::UuidDefinition::Presenter.new(waml_definition: @waml_definition)

  if uuid_presenter.render?
    migrations << {
      path: uuid_presenter.file_name((migration_timestamp + migration_count).strftime('%Y%m%d%H%M%S')),
      content: uuid_presenter.render
    }

    migration_count += 1
  end

  active_storage_presenter = ::WebammToRails::Sources::Migrations::ActiveStorageDefinition::Presenter.new(waml_definition: @waml_definition)

  if active_storage_presenter.render?
    migrations << {
      path: active_storage_presenter.file_name((migration_timestamp + migration_count).strftime('%Y%m%d%H%M%S')),
      content: active_storage_presenter.render
    }

    migration_count += 1
  end

  models_order = []

  @database_tables.each do |model|
    depending_on = @waml_definition.database.relationships.select { |r| r.source == model.table && r.type == 'belongs_to' }.map(&:destination)
    models_order << { model: model.table, depending_on: depending_on }
  end

  models_hash = models_order.each_with_object({}) do |model, hash|
    hash[model[:model]] = model
  end

  # Topological Sort
  sorted_models = []
  visited = {}
  temp_marks = {}
  
  models_order.each do |model|
    visit(model[:model], models_hash, sorted_models, visited, temp_marks)
  end

  sorted_models.each do |attrs|
    table_name = attrs[:model]
    db_table = @database_tables.find { |t| t.table == table_name }

    migration_code = ::WebammToRails::Sources::Migrations::Definition.new(
      table_definition: db_table, waml_definition: @waml_definition
    ).render
    
    migrations << {
      path: "db/migrate/#{(migration_timestamp + migration_count).strftime('%Y%m%d%H%M%S')}_create_#{db_table.table}.rb",
      content: migration_code
    }

    migration_count += 1
  end

  migrations
end